Listing 4. Program to Redirect Browser to Highest Numbered File
#!/usr/bin/perl -wT
# program redirects the user's browser to the
# highest-numbered file matching the pattern
# file-n.html.
use strict;
use vars qw($query $directory @files $url $a_number $b_number);
use diagnostics;
use CGI; # from http://www.perl.com/CPAN/
# Create an instance of CGI
$query = new CGI;
# Directory in which the documents reside
$directory = "/usr/local/apache/share/htdocs/";
# Open the directory
if (opendir(DIR, $directory))
{
# Grab all of the "file-n.html" files, sort
# them by n, and put them in @files
@files = sort by_number
grep {/^file-[0-9]+\.html$/} readdir(DIR);
# Close the directory
closedir DIR;
}
else
{
&log_and_die("Problem opening \"$directory\": $!");
}
# Grab the name of the highest file, and create a
# URL based on it
$url = "/" . $files[$#files];
# Redirect the user to the appropriate graphic
print $query->redirect($url);
sub log_and_die
{
# Get the message
my $message = shift;
# Print the error message to the user's
# browser
print $query->header("text/html");
print $query->start_html(-title => "Error!");
print "<P>$message</P>\n";
print $query->end_html;
}
sub by_number
{
# Grab the first file's number
if ($a =~ /^file-(\d+).html$/)
{
$a_number = $1;
}
# Grab the second file's number
if ($b =~ /^file-(\d+).html$/)
{
$b_number = $1;
}
# Compare the numbers
return ($a_number <=> $b_number);
}
Copyright © 1994 - 2018 Linux Journal. All rights reserved.