In the concluding article in the Perl 101 series, everythingyou've learnt so far is put to the test when you develop some real-worldCGI applications - a counter, a guest book and a form mailer.
So that takes care of data entry. But how about the link that allows the user to read previous guestbook entries? Well, here's the code for the CGI script that reads the file and displays all previous entries to the user.
#! /usr/bin/perl
# view.cgi - display guestbook entries
# open the file and read contents into an array
open (GBOOK, "guestbook.txt");
@entries = <GBOOK>;
close (GBOOK);
print "Content-Type: text/html\n\n";
print "<html><body>";
print "<center>";
print "<table cellspacing=5 cellpadding=5 width=600 >";
print "<tr><td align=center width=600><font face=Verdana size=2>View other
comments.</font></td></tr>\n";
# at this point, each entry in the file is stored as a single element of
the array
foreach $entry(@entries)
{
# use chomp() to delete the newline character from the end of each line
chomp $entry;
# split each array element against the # delimiter into a new temporary
array
# now, the first element of the temp array contains the name
# the second, the email address and the third, the comment
@singles = split (/#/, $entry);
# display it
print "<tr><td width=600>";
print "<table cellspacing=5 cellpadding=0 width=600 bgcolor=#D6D6D6><tr
><td align=right width=300 ><font face=Verdana size=2>Name:</font></td><td
align=left width=300><font face=Verdana
size=2>$singles[0]</font></td></tr>\n";
print "<tr><td align=right width=300><font face=Verdana size=2>Email
address:</font></td><td align=left width=300><font face=Verdana
size=2>$singles[1]</font></td></tr>\n";
print "<tr><td align=right width=300 valign=top><font face=Verdana
size=2>Comments:</font></td><td align=left width=300><font face=Verdana
size=2>$singles[2]</font></td></tr></table>\n";
print "</td></tr>";
}
print "</body></html>";
Now, when it's time to display the contents of the guestbook,
we do things in reverse: first read the file into an array, split each element against the # delimiter we added earlier, and display it in a neatly formatted table. Simple, huh?
This article copyright Melonfire 2000. All rights reserved.