Sample solutions and discussion
Perl Quiz of The Week #14 (20030611)
Write a program which generates an HTML table of contents for
a directory of files. It should read the directory, producing
a list of the files, and write out a file "toc.html" in that
same directory, in the following format:
Table of Contents for [Directory Name]
Table of Contents for [Directory Name]
file1
file2
...
lastfile
The files should be listed in alphabetic order. The program
should accept a command-line argument that tells it what
directory to index; if the argument is omitted, it should
index the current directory.
----------------------------------------------------------------
I only saw one solution posted on the perl-qotw-discuss list, from
Pr. Offer Kaye; I also wrote one myself. Offer's uses a number of
standard modules to take care of escaping HTML and URLs:
use strict;
use warnings;
use Cwd;
use URI::file;
use HTML::Entities;
my $toc_file = "toc.html";
if ($#ARGV > 0) {die "Incorrect usage. Use \"$0 dir_name\" or just:
\"$0\"\n"}
my $dir_name = ($#ARGV == 0) ? $ARGV[0] : cwd();
opendir(DIR, $dir_name) or die "Can't opendir $dir_name: $!\n";
my @list = sort {lc($a) cmp lc($b)} readdir(DIR);
chdir $dir_name or die "Couldn't chdir to $dir_name for some reason...\n";
open(OUT,">$toc_file") or die "Couldn't open $toc_file for writing: $!\n";
print OUT "Table of Contents for ";
print OUT encode_entities($dir_name),"\n";
print OUT "Table of Contents for ";
print OUT encode_entities($dir_name),"
\n";
for (@list){
next if (($_ eq ".") or ($_ eq ".."));
my $u = encode_entities(URI::file->new($_));
print OUT "\n";
}
print OUT "";
Most of this seems completely straightforeard and I don't have much to
say about it.
I wonder about using 'cwd()' instead of just '.'. I suppose '.' might
not be portable, but if you want it to be portable, it would seem to
be to be simpler to use File::Spec->curdir(), which then just returns '.'.
The output from Pr. Kaye's program is a little peculiar if the
filenames are peculiar. For example, I created a file named
'