CGI and Perl

Listing 16.1. A very simple calculator

#!/usr/local/bin/perl
 use CGI::Form;
 $q = new CGI::Form;
 print $q->header();
 print $q->start_html(-title=>`A Very Simple Calculator');
 print "<H1>A Very Simple Calculator</H1>\n";
 if ($q->cgi->var(`REQUEST_METHOD') eq `GET') {
    $val=0;
    &printForm($q,$val);
 } else {
    $val=$q->param(`hiddenValue');
    $modifier=$q->param(`Modifier');
    if ($modifier=~/^[\d]+$/) {
       $op=$q->param(`Action');
       if ($op eq "Add") {
          $val+=$modifier;
       } elsif ($op eq "Subtract") {
          $val-=$modifier;
       } elsif ($op eq "Multiply") {
          $val*=$modifier;
       } elsif ($op eq "Divide") {
          $val/=$modifier;
       }
    } else {
       print "<P><STRONG>Please enter a numeric value!</STRONG><BR><BR>\n";
    }
    $q->param(`hiddenValue',$val);
    &printForm($q,$val);
 }
 print $q->end_html();
 sub printForm {
    my($q,$val)=@_;
    print "<P>The current value is: $val\n";
    print "<P>Please enter a value and select an operation.\n<BR>";
    print $q->start_multipart_form();
    print $q->hidden(-name=>`hiddenValue',-value=>$val);
    print "<TABLE><TR><TD COLSPAN=4>\n";
    print $q->textfield(-name=>`Modifier',-size=>12,-maxlength=>5);
    print "</TD></TR>\n<TR><TD>\n";
    print $q->submit(-name=>`Action',-value=>`Add');
    print "\n</TD><TD>\n";
    print $q->submit(-name=>`Action',-value=>`Subtract');
    print "\n</TD><TD>\n";
    print $q->submit(-name=>`Action',-value=>`Multiply');
    print "\n</TD><TD>\n";
    print $q->submit(-name=>`Action',-value=>`Divide');
    print "\n</TD><TD>\n";
    print "</TR></TABLE>\n";
    print $q->end_form;
 }

You will note that in this example, we use the hidden field Value to retain the current value of the calculator. We do some very basic field validation to make sure the user actually gave us a number. Obviously, this calculator will accept only integer values. Remember that when the user leaves our CGI program and returns, all state is now lost. Figure 16.1 shows the calculator as it appears in the Web browser.

Let's look at another example now in Listing 16.2 that will make use of a file to retain state about a certain client. We will use the REMOTE_ADDR CGI environment variable to distinguish between clients. In this example, we will be allowing users to enter our Web site and write whatever they like in a big text field and then store the contents of that field in a file for them to later come back to and modify. Additionally, we will keep track of how many times users submitted changes to their text and display that value to them. Our example will simply use the /tmp/visitors directory to store these files and not worry about cleaning up these files.

Figure 16.1. The calculator example in the browser.