http://www.perlmonks.org?node_id=133599


in reply to How do I read 5 lines from a file that's read from a directory that's being listed

The obvious question: what doesn't work? You don't tell us exactly what the error is. In any event, I cleaned up your code a bit (but just a bit):

#!/usr/bin/perl -w use strict; use CGI qw/:all/; use URI::Escape; print header; use constant TEMPLATE => "../htdocs/template2.html"; use constant HOME => "../htdocs/archive/"; open HTMLFILE, ">", TEMPLATE or die "Open ".TEMPLATE." failed: $!" +; print HTMLFILE <<END_HTML; <HTML> <HEAD> <TITLE>Updated Page</TITLE> </HEAD> <BODY> <CENTER> <FONT SIZE='5' FACE='ARIAL'>List of files</FONT> </CENTER> <BR> <font size='2' face='arial'> END_HTML opendir HOMEDIR, HOME or die "Unable to open directory '".HOME."': + $!"; my @files = grep !/^\./, readdir(HOMEDIR); closedir HOMEDIR; foreach my $file (reverse sort @files) { print HTMLFILE a({ -href => uri_escape('archive/'.$file)}, esc +apeHTML($file)), br, "\n"; #the upper part of this code reads/prints the list of files an +d links them #the next part of this code reads 5 lines of a file open STUFF, "<", HOME.$file or die "Unable to open ".HOME.$fil +e.": $!"; while(<STUFF>) { 1 .. 5 ? print HTMLFILE: last; } close STUFF; } print HTMLFILE "</font></BODY></HTML>"; close HTMLFILE; print "hopefully this works";

Note the URI::Escape routine for generating proper HREFs was taken from Dump a directory as links from CGI.

The only thing that I can reasonably see that might be your problem is this line:

print HTMLFILE "<a href=/archive/$file>$file</a><br>\n";

Did you really mean to put that slash in front of archive? That makes that URL relative to root, whereas I think you want it relative to htdocs. I took the slash out in my version. I also left in your HTML (albeit reluctantly). It should probably be converted to CGI.pm's HTML generating functions or put into a *proper* template. I suggest that you look into HTML::Template or Template Toolkit.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.