#!/usr/bin/perl -w ###################################### # # guestbook2.cgi # # Use CGI.pm for headers and some html code, and for parsing parameters. # Use a tied hash for the file input/output. # # - Jim Mahoney, Jan 2002 ####################################### use CGI; use CGI::Carp qw(fatalsToBrowser); # Send "die" messages to browser window my $cgi = new CGI; # One way of using CGI.pm - object oriented. print $cgi->header(); # standard CGI headers # Get the parameters. my $name = $cgi->param('name'); # Let CGI.pm do parsing of parameters. my $message = $cgi->param('message'); # This works for POST or PUT forms. # Perl has a "tie" function that replaces hash access # with file read write. In other words, once a hash is "tied", # then # $hash{key}="stuff"; # this writes to the file # $a = $hash{key}; # this reads from the file # The details for how the file is organized are handled by somebody else. #use DB_File::Lock; use DB_File; my %guesthash; my $guestfile = 'guestbook2.db'; # Append the date and message to our guestbookfile # using a Berkely database file and a tied hash. if ($message and $name) { my $key = time() . $name; my $date = scalar localtime(); my $text = " Posted by '$name' on $date :

$message

\n\n"; # tie %guesthash, 'DB_File::Lock', $guestfile, O_RDRW, 0666, $DB_HASH, 'write'; tie %guesthash, 'DB_File', $guestfile, O_RDRW, 0666, $DB_HASH; $guesthash{$key} = $text; untie %guesthash; } # Read in the data from the file. # # This kind of file-ish database is particularly efficient # for reading only part of the file - though that's not what # we're doing here. See the DB_File::Lock and DB_File CPAN docs # for the details. # This mechanism wants to create a file in this directory. # So (the easiest way out) I made the whole directory world writable. (Ouch.) # There are ways to specify a lock file explicitly; but I didn't bother. # tie %guesthash, 'DB_File::Lock', $guestfile, O_RDONLY, 0666, $DB_HASH, 'read'; tie %guesthash, 'DB_File', $guestfile, O_RDONLY, 0666, $DB_HASH; my $gueststring=''; (my @keys = sort keys %guesthash) or $gueststring = "No Messages\n"; foreach my $key (@keys) { $gueststring .= $guesthash{$key} . "\n"; } untie %guesthash; # Print out the web page, including the form to submit more stuff # We can, if we like, use CGI.pm to generate a lot of this HTML code. print $cgi->start_html('Guest Book 2'); print "

Guest Book 1

So. Ya wanna sign the guest book? "; print $cgi->start_form(); print "
Your Name:
Message:
 
"; print $cgi->end_form(); print "

$gueststring
"; print $cgi->end_html(); exit;