Web Automation: Generating Dynamic Tables of Contents Page 5

By Matthew Keller (Send Email)
Posted Jun 21, 2000


You don't even have to run this as a CGI. You can run it from the command line and output the results to an HTML file that you have in your webspace. This allows you to periodically generate this table of contents file, without having millions of users hammering your CGI. For example you could have cron, or any other scheduling service periodically execute the command perl toc.pl > /usr/local/apache/htdocs/toc.html--which will rebuild your table of contents. Pointing users to the toc.html page might not give them a real-time view of your webspace, but might be more feasible.

I'd also like to shamelessly plug Lincoln Stein's CGI.pm module, which is available on CPAN, and probably is already in your Perl distribution. I use this module to take a lot of the HTMLizing out of my hands. I wrote this example using no modules, so you could see what was going on, but I highly recommend using CGI.pm to do a lot of the HTML stuff for you.

Full Text of this Example

1: #!/usr/bin/perl -w
2: sub Get_Title {
3: my $filename=shift;
4: unless(-f "$filename") { return("NO INDEX"); }
5: open(HTML,"<$filename");
6: while(<HTML>){
7: if($_=~ /<title>(.*)<\/title>/i) {
8: close HTML;
9: return "$1";
10: }
11: }
12: close HTML;
13: return "Untitled";
14: }
15: sub Get_Dirs {
16: my $basedir=shift;
17: opendir(GD,"$basedir") or return;
18: my @DIRS;
19: for(readdir(GD)) {
20: my $temp="$_";
21: if($temp =~ /^\./) { next; }
22: if(-d "$basedir$temp") {
23: push(@DIRS,"$basedir$temp/");
24: }
25: }
26: closedir GD;
27: return @DIRS;
28: }
29: sub Get_Depth {
30: $_ = shift;
31: return tr/\///;
32: }
33: my $dir="/home/html/mattwork/htdocs/";
34: my $url="http://mattwork.potsdam.edu/";
35: my $depth=Get_Depth("$dir")+1;
36: my @dirs=Get_Dirs("$dir");
37: print "Content-Type: text/html\n\n";
38: print "<html><head><title>Table of Contents</title></head><body>\n";
39: print "<ul>\n";
40: while(@dirs) {
41: my $currdir=shift(@dirs);
42: my $currdepth=Get_Depth("$currdir");
43: unshift(@dirs,Get_Dirs("$currdir"));
44: if($currdepth > $depth) { print "<ul>\n"; }
45: if($currdepth < $depth) {
46: $diff=$depth - $currdepth;
47: print "</ul>\n" x $diff;
48: }
49: $depth=$currdepth;
50: my $path="$currdir" . "index.html";
51: unless(-e "$path") { next; }
52: my $title=Get_Title("$path");
53: $path =~ s/$dir/$url/i;
54: print "<li><a href=\"$path\">$title</a></li>\n";
55: }
56: print "</ul>\n";

Page 5 of 5


Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.