Perl CGI: The Happy Path: Inner Loop Solution
Prepared by Bill Kilgallon,
Bill@KilgallonFamily.com
Solution
#!C:\PERL\BIN\PERL.EXE
# The line above is called the shebang line. It tells the server where
# to find the executable program to be used to interpret the commands in
# this text file. In this case, this file is a perl program and should
# be processed with the Perl interpreter program.
# Tell Perl we want to use one of it's helper modules. In this case,
# the CGI module simplifies lots of the steps necessary to generate
# html instructions as output.
use CGI;
# This is another handy module to use. It tells perl to be pretty
# fussy about syntax and complain a lot. This sounds like a bad
# thing, but if you think about it, the only thing worse then a broken
# perl program complaining about lots of little problems is a broken
# perl program that just does the wrong thing without a whimper. Fussy
# and verbose programs are much easier to debug.
use strict;
# This, for the time being, is magic. We are creating a CGI object
# and naming it "query". We will use this object as a helper to do
# most of the actual html work of our program. We could do it all by
# hand if we wanted, but some really smart people have written some
# really nice tools, and we would be fools to ignore them.
my $query=new CGI;
# Create a header, and let it default arguments, it likely knows
# better then we do.
print $query->header();
# Start the body of our document, and give it a title (shows up on the
# browser bar and on printouts). All the legal fields within the HTML
# "BODY" tag are supported, and are optional. Other unsupported
# options can be specified as well, and will be correctly added. Note
# that there is nothing actually in the body tag, just HTML modifiers
# being specified.
print $query->start_html({-title=>'Web Counter',
-author=>'Bill Kilgallon'});
print $query->div({-align=>'center'});
print $query->h1('Hello World!');
print $query->hr();
# Open a file for reading....
open(COUNTERFILE, "<counterfile.txt");
# And load the number that we last stored in it.
my $count = <COUNTERFILE>;
# And close the file
close(COUNTERFILE);
# Increment our count
$count++;
# Open the same file again, but this time truncate it for writing.
open(COUNTERFILE, ">counterfile.txt");
# Write our new count into the file
print COUNTERFILE "$count\n";
# And close the file.
close(COUNTERFILE);
# Now we can output the information we have gleaned...
print $query->hr();
print $query->h2("You are visitor number $count\n");
print $query->hr();
# And finally, end the document.
print $query->end_html;
Return to Index