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.
Here's the other half of the puzzle - the CGI script that takes care of the actual storage of form data.
#! /usr/bin/perl
# submit.cgi - accepts guestbook data and writes to file
# define a variable that accepts a value from the form
$in;
# assign values to the variable depending on form METHOD
if ($ENV{'REQUEST_METHOD'} eq "GET") {
$in = $ENV{'QUERY_STRING'};
} else {
$in = <STDIN>;
}
# fix URL-encoded strings
$in =~ s/\+/ /g;
# all variables are passed to the script as name-value pairs separated by &
# split the input string on the basis of &
@detail = split (/&/, $in);
# display data entered by user again
print "Content-Type: text/html\n\n";
print "<html><body>";
print "<center>";
print "<table cellspacing=5 cellpadding=5 width=600 bgcolor=#D6D6D6>";
print "<tr><td align=center colspan=2 width=600><font face=Verdana
size=2>Thank you for entering the following details in the
guestbook.</font></td></tr>\n";
# each name-value pair is stored as an element of an array
# now take each element of the array and split to form a hash
# on the basis of the = symbol
# using the "foreach" loop, we split each element of the array into a
"temporary" hash
foreach $details(@detail)
{
%details = split (/=/, $details);
# now extract the name-value pair from the temporary hash to display to the
user
# some forward thinking here:
# since values need to be stored in a text file, create a variable called
$entry
# and differentiate the different elements of each guestbook entry by the #
symbol
# this comes in useful later, wait and see!
while (($name, $value) = each %details)
{
print "<tr><td align=right width=300><font face=Verdana size=2>Your
$name:</font></td><td align=left width=300><font face=Verdana size=2>
$value</font></td></tr>\n";
$entry .= $value . "#";
}
}
# end the display with a link that allows the user to view other guestbook
entries
print "<tr><td align=center colspan=2 width=600><font face=Verdana
size=1>Click <a href= view.cgi>here</a> to view other
entries.</font></td></tr></table>";
print "</body></html>";
# make things simple by ensuring that every entry in the file is on a
single line
# by terminating the entry with a newline
$entry = $entry."\n";
# this is where the file write actually happens
# remember to open the file in "append" mode to avoid losing previous data
# make sure that you have permission to write to this file
open (GBOOK, ">> guestbook.txt");
print GBOOK "$entry";
close (GBOOK);
# whew!
Now, how about an explanation?
This article copyright Melonfire 2000. All rights reserved.