CGI and Perl

Constructing Elements

You have seen a few examples of how to define fields using CGI::Form. Now let's look at an example of a complete form. What you'll do is create a general questionnaire form for a restaurant. You'll ask the user these things: What did you order? (text field)

How was the service? (radio group)

How did the food taste? (radio group)

What is your age group? (popup menu)

 Would you come back again? (checkbox)

The Perl code in Listing 4.1 generates these fields using a multipart/form-data type form.

Listing 4.1. Perl code for customer questionnaire.

 use CGI::Form;
 $q = new CGI::Form;
 print "<H1>Customer Survey</H1>\n";
 print $q->start_multipart_form();
 print "What did you order? ";
 print $q->textfield( -name=>'order', -value=>"", -maxlength=>30, -size=>30 );
 print "<BR>"; # Line break
 print "How was the service? (5-good,1-bad) ";
 print $q->radio_group( -name=>'serviceRating', -values=>[`1','2','3','4','5'],
                        -default=>'3' );
 print "<BR>";
 print "How did the food taste? (5-good,1-bad) ";
 print $q->radio_group( -name=>'tasteRating', -values=>[`1','2','3','4','5'],
                        -default=>'3' );
 print "<BR>";
 print "What age group are you in? ";
 @ages=( `child', `teen', `20s', `30s', `40s', `50s', `senior' );
 print $q->popup_menu( -name=>'ageGroup', -values=>\@ages );
 print "<BR>";
 print $q->checkbox( -name=>'comeAgain', -checked=>'checked', -value=>'yes',
                     -label=>"I would come back again " );
 print "<BR><BR>";
 print $q->submit( -name=>'Action', -value=>'Submit' );
 print $q->reset();
 print $q->endform();

This form appears in the browser, as shown in Figure 4.1.

You can include more than one form on a single HTML page. Each form can be associated with separate actions or the same action.

Figure 4.1. The questionnaire as it appears in the browser.