Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

write html code with perl

by lenieto3 (Acolyte)
on Mar 01, 2014 at 01:32 UTC ( #1076640=perlquestion: print w/replies, xml ) Need Help??

lenieto3 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm working in a basic html page, actually it is just a list of links to some pictures.

<html> <head> <link type="text/css" rel="stylesheet" href="style/sty +lesheet.css"/> </head> <body> <ul> <li><a target="_blank" href="images/patecumbia +.png">Patecumbia</a></li> <li><a target="_blank" href="images/ +g">Trapped</a></li> <li><a target="_blank" href="images/navaja_for +ce.png">Navaja Force</a></li> <li><a target="_blank" href="images/que_esta_p +asando.png">&iquest;Qu&eacute; est&aacute; pasando?</a></li> <li><a target="_blank" href="images/the_look.p +ng">The Look</a></li> <li><a target="_blank" href="images/ +g">Hablame</a></li> </ul> </body> </html>

I just loaded some new pictures in my images directory and I want to update my web page, as it is a really repetitive work I'll like to use a perl script for doing it.

I want to replace all the lines between the ul tags for just a perl script that reads the files under the images directory and give me the html lines that I need.

I'm working in this script, but how can I do for embedding its output into the html page?. Thanks monks

Thanks for your answers, but I was thinking in something like the php opening and closing tags. Can perl be used like this way?

Replies are listed 'Best First'.
Re: write html code with perl
by kcott (Bishop) on Mar 01, 2014 at 06:30 UTC

    G'day lenieto3,

    I created an images directory with these dummy files:

    asd_fgh_jkl.png qwerty.png uiop.png zxcv_bnm.png

    This script:

    #!/usr/bin/env perl use strict; use warnings; my $ul = 0; while (<DATA>) { $ul = 0 if /<\/ul>/; next if $ul; print; if (/<ul>/) { $ul = 1; for (glob 'images/*.png') { my @name = map { "\u$_" } split /_/ => (/images\/(.+)\.png +/)[0]; print qq{ <li><a target="_blank" href="$_">@nam +e</a></li>\n}; } } } __DATA__ <html> <head> <link type="text/css" rel="stylesheet" href="style/stylesheet. +css"/> <title></title> </head> <body> <ul> <li><a target="_blank" href="images/patecumbia.png">Patecu +mbia</a></li> <li><a target="_blank" href="images/trapped.png">Trapped</ +a></li> <li><a target="_blank" href="images/navaja_force.png">Nava +ja Force</a></li> <li><a target="_blank" href="images/que_esta_pasando.png"> +&iquest;Qu&eacute; est&aacute; pasando?</a></li> <li><a target="_blank" href="images/the_look.png">The Look +</a></li> <li><a target="_blank" href="images/hablame.png">Hablame</ +a></li> </ul> </body> </html>

    Produced this output:

    <html> <head> <link type="text/css" rel="stylesheet" href="style/stylesheet. +css"/> <title></title> </head> <body> <ul> <li><a target="_blank" href="images/asd_fgh_jkl.png">Asd F +gh Jkl</a></li> <li><a target="_blank" href="images/qwerty.png">Qwerty</a> +</li> <li><a target="_blank" href="images/uiop.png">Uiop</a></li +> <li><a target="_blank" href="images/zxcv_bnm.png">Zxcv Bnm +</a></li> </ul> </body> </html>

    That's pretty much what you want except for link names like "&iquest;Qu&eacute; est&aacute; pasando?": you'd need to set up rules for those; if there's only a few, manual editing may be less effort than writing the code.

    -- Ken

      Hi Ken. Regarding your closing remark about character entities for the non-ASCII characters, I think one rule will suffice: use HTML::Entities. It has an "encode_entities" function that can convert utf-8 characters in a given range to their "symbolic" entity-references:
      perl -MHTML::Entities=encode_entities -e 'print encode_entities("\x{00 +bf}Que?")'

      (Update: to clarify: if the files to be listed already have quaint names with non-ASCII utf8 characters in them, then adding HTML::Entities::encode_entities will make sure those names will display correctly without having to worry about a given browser's default character-set; but if the string descriptions to be displayed are different from the actual file names used, then there would need to be some sort of look-up table for that.)

        "Regarding your closing remark about character entities for the non-ASCII characters, I think one rule will suffice: use HTML::Entities. ..."

        Use of HTML::Entities was my first thought too; however, the one line that didn't follow the general pattern seemed so different, that I decided to suggest special rules or manual editing.

        For all lines (except the que_esta_pasando.png one), the "my @name = ..." line seemed to embody the general pattern to the extent possible from the code provided by the OP: trapped.png becomes Trapped, the_look.png becomes The Look, and so on.

        For the que_esta_pasando.png line, the general pattern is not applied beyond splitting on underscores. I think your "Update" alludes to this but I thought I'd point out the differences, as I see them, in this specific case.

        • Split on underscores (as for other lines): "que_esta_pasando.png" becomes "que esta pasando"
        • Know this is a foreign language. [I've assumed Spanish; happy to be corrected; it doesn't change the point I'm making.]
        • Apply the appropriate diacritical marks for this language: "que esta pasando" becomes "qué está pasando"
        • Treat as a sentence, not as a title, so only the first word is capitalised: "qué está pasando" becomes "Qué está pasando"
        • Know enough of this language to understand that this sentence is a question, not a statement. Apply the appropriate punctuation for a question in this language: "Qué está pasando" becomes "¿Qué está pasando?"
        • Not shown, but adding a lang="es" attribute would probably also be appropriate.

        All of this could be coded and, for some massive international image library with ongoing maintenance requirements, may well be the way to go. However, the OP states "I'm working in a basic html page, actually it is just a list of links to some pictures.": in this instance, rules (such as a lookup table which you've suggested) or manual editing seems more sensible and a lot less work.

        -- Ken

Re: write html code with perl
by zentara (Archbishop) on Mar 01, 2014 at 11:21 UTC
    Don't forget the usefulness of interpolated heredocs '<<' in generating html. See heredocs
    #!/usr/bin/perl use warnings; use strict; #this one accounts for pics with no text file umask 0022; #do a simple glob for .txt files my @tfiles = <*.txt>; (@tfiles) = map{ $_ =~ /(.*).txt$/ } @tfiles; print "text-> @tfiles\n"; #assume photos are in subdir pics/* #do a simple glob for .jpg files my @jfiles = <pics/*.jpg>; (@jfiles) = map{ $_ =~ /pics\/(.*).jpg$/ } @jfiles; print "jpg-> @jfiles\n"; #now find which pics don't have a txt file my %h; # Initialise the hash using a slice @h{@tfiles} = undef; @jfiles = grep {not exists $h{$_}} @jfiles; print "stray jpg-> @jfiles\n"; #now push the stray photo onto the end of the @tfiles push @tfiles,@jfiles; print "all html-> @tfiles\n"; foreach my $file (@tfiles) { open(HH, "> $file.html") or warn "$!\n"; my $text = ''; #print headline print HH<<EOH; <html> <BODY TEXT="#FFCCCC" BGCOLOR="#000000"> <center><h1>$file</h1></center> EOH #print jpg if exists if( -e "pics/$file.jpg"){ print HH<<EOI; <center><IMG SRC="pics/$file.jpg" alt="[$file.jpg]"></center> EOI }else{ print HH<<EOI; <center><IMG SRC="" alt="[No Image Available]"></center> EOI } #print text if exists if( -e "$file.txt"){ open(TH, "< $file.txt") or warn "$!\n"; read( TH, $text, -s TH ); close TH; print HH<<EOT; <center> <pre> $text </pre> </center> EOT } print HH<<EOHTML; </body> </html> EOHTML close HH; }

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: write html code with perl
by thomas895 (Chaplain) on Mar 01, 2014 at 21:56 UTC

    Consider a template-based approach, so that you can easily change your layout later. For example, using HTML::Template, see the following:

    use strict; use warnings; use HTML::Template; use File::Basename qw(fileparse); my $tmpl = HTML::Template->new(filehandle => *DATA); my @images = (); foreach(glob 'images/*.png') { push @images, +{ file => $_, name => basename($_) #you will probably want to get your name +from a more interesting source; see below }; } $tmpl->param(images => \@images); print $tmpl->output(); __DATA__ <html> <head> <title>images</title> </head> <body> <ul> <TMPL_LOOP NAME=images> <li><a href="<TMPL_VAR NAME=file>" target="_blank"><TMPL_VAR N +AME=name ESCAPE=HTML></a></li> </TMPL_LOOP> </ul> </body> </html>

    Another great resource is HTML::Template Tutorial, linked from the HTML::Template docs.

    "Excuse me for butting in, but I'm interrupt-driven..."
Re: write html code with perl
by Anonymous Monk on Mar 01, 2014 at 01:51 UTC

    I'm working in this script, but how can I do for embedding its output into the html page?. Thanks monks

    Its simple, create a new file use Path::Tiny qw/ path /; path( '/foo/bar.html' )->spew_utf8( $the_new_html );

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1076640]
Approved by davido
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2020-01-18 18:59 GMT
Find Nodes?
    Voting Booth?