Friday, April 04, 2003

File tests and Directory operations (S&P -- Chapters 11 and 12)

The script below, when run on one of the CS machines will generate a file in the current directory named course.html which contains all the 3710 course notes in a single web page.

There are, however, a few problems with the generated file:

Despite the above shortcomings, the script demonstrates many new features in Perl that we have not seen yet. In particular, it demonstrates the use of file tests, some directory operations, extracting user information from the password file, file globbing, and the special variable $/.


#!/usr/bin/perl -w

use strict;

my $output = "course.html";
die "File '$output' exists!" if -e $output;
open OUT, "> $output" or die "Cannot open '$output': $!\n";

print OUT "<html>\n<body>";

defined(my $dir = (getpwnam("donald"))[7]) or die "No such user!";

$dir .= "/.www/comp3710/diary/2003";
die "No such directory '$dir'" if ! -d $dir;

chdir $dir or die "Cannot change to '$dir': $!\n";

undef $/;

for (glob "*/*/index.html") {
	if (! -r) {
		print "File $_ is not readable.";
		last;
	} elsif (! -s) {
		print "File $_ is empty.";
		next;
	}
	open HTML, $_ or die "Cannot open file '$_': $!\n";
	my ($html) = (<HTML> =~ m{<body>(.*)</body>}s);
	close HTML;
	print OUT $html;
}
print OUT "</body>\n</html>";
close OUT;


Last modified: Fri Apr 4 15:31:09 2003