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

Hello, I am trying to find a way to take a list of html files in a directory and make them into HTML hyperlinks for printing as HTML output.

opendir DIR, "directory/"; my @files = grep { $_ ne '.' && $_ ne '..' } readdir DIR; closedir DIR;

Are there any Perl modules that could help do the processing or will I have to procedural processing for each elements into a href links? This is relatively easy I think, except when naming the link as I would like to keep the url link name the path of the file or at least the file name. I want to be able to have the cgi script then do something like this to print the links

print <<ENDHTML; @array ENDHTML

Thanks in advance.

Replies are listed 'Best First'.
Re: Turn list of files from directory into hyperlink
by kcott (Archbishop) on Apr 14, 2013 at 03:07 UTC

    G'day herpderpderp,

    Welcome to the monastery.

    The basic coding for this is pretty straightforward:

    $ perl -Mstrict -Mwarnings -E ' my @dir_files = qw{. .. .hidden.html a.txt b.pdf c.html d.pl e.sql + f.xml g.h.i.html}; my @files = grep { ! /^[.]{1,2}$/ and /[.]html$/ } @dir_files; say qq{<a href="$_">$_</a>} for @files; ' <a href=".hidden.html">.hidden.html</a> <a href="c.html">c.html</a> <a href="g.h.i.html">g.h.i.html</a>

    Modules that might help with this: File::Find (Builtin Module); File::Find::Rule (CPAN Module).

    -- Ken

Re: Turn list of files from directory into hyperlink
by NetWallah (Canon) on Apr 14, 2013 at 04:30 UTC
    The canonical way to generate links is to use the "a" (anchor) function of the CGI module:
    use CGI qw/:standard /; use File::Basename; my @links = map { a( {-href=>$_}, fileparse($_)[0] ) } @files;
    Then , if you want to print the links in an html table, CGI provides the perlish way to do that:
    print table({-border=>undef}, caption('List of files on this server'), map ({ Tr({-align=>'CENTER',-valign=>'TOP'}, td($_)) } @links ) ), "\n";

                 "I'm fairly sure if they took porn off the Internet, there'd only be one website left, and it'd be called 'Bring Back the Porn!'"
            -- Dr. Cox, Scrubs

Re: Turn list of files from directory into hyperlink
by Kenosis (Priest) on Apr 14, 2013 at 04:24 UTC

    Perhaps the following will be helpful:

    use strict; use warnings; use File::Glob qw/:nocase/; use File::Basename; my @htmlFiles = map { my $file = fileparse $_; qq{<a href="$file">$_</ +a><br>\n} } <directory/*.{htm,html}>; print for @htmlFiles;

    Sample output:

    <a href="67.htm">directory/67.htm</a><br> <a href="5a.html">directory/5a.html</a><br> <a href="a.HTML">directory/a.HTML</a><br>
Re: Turn list of files from directory into hyperlink
by ig (Vicar) on Apr 14, 2013 at 07:57 UTC