CGI and Perl

Processing the POST

When the user clicks Submit, the form data is sent back up to the server and the Perl script is called with the request method POST. All the values in the form can be obtained using the param() method. The Perl subroutine in Listing 7.2 gathers all the information into a single record of data and returns the delimited string that makes up a row in the database.

Listing 7.2. Perl subroutine to process the form data.

sub gatherData {
    my($q)=@_;
    my(@orderedList)=();
    push(@orderedList,$q->param(`Name'));
    push(@orderedList,$q->param(`Title'));
    push(@orderedList,$q->param(`Company'));
    push(@orderedList,$q->param(`Address'));
    push(@orderedList,$q->param(`City'));
    push(@orderedList,$q->param(`State'));
    push(@orderedList,$q->param(`ZipCode'));
    push(@orderedList,$q->param(`Phone'));
    push(@orderedList,$q->param(`Fax'));
    push(@orderedList,$q->param(`email'));
    push(@orderedList,$q->param(`How'));
    push(@orderedList,$q->param(`What'));
    push(@orderedList,$q->param(`Comment'));
    return join(`<*>`,@orderedList);
 }

Putting It All Together

The main code in the guest book program is now pretty simple. All you need to do is figure out whether you're handling a GET or a POST and do the appropriate thing. An environment variable called REQUEST_METHOD tells you whether it is POST or GET. You obtain the value of this environment variable using the var() method of the inherited CGI::Base class. Assume you keep the database in a file called guests.list. You can now put this whole thing together with just a few lines of code, as shown in Listing 7.3.

Listing 7.3. Main Perl guest book CGI program.

#!/public/bin/perl5
 # Standard header stuff
 use CGI::Form;
 $q = new CGI::Form;
 print $q->header();
 print $q->start_html(-title=>`Welcome to Widget World',
                     -author=>`webmaster\@widgets.com');
 if ($q->cgi->var(`REQUEST_METHOD') eq `GET') {
    &guestBookForm($q);
 } else {
    open(DATABASE,">> guests.list") ||
       die "Cannot open guest book list for append!\n";
    print DATABASE &gatherData($q);
    print DATABASE "\n";
    close(DATABASE);
    print "<P>Thank you for taking the time to enter our guest book! ";
    print "We look forward to doing business with you.";
 }
 print "<HR>\n<P>If you have any problems with this form, please contact ";
 print "our <A HREF=mailto:webmaster\@widgets.com>Web master</A>";
 print $q->end_html();