9.1.4 Accessing field values

Observe the following code (based on the original text field sample script):

#!/usr/bin/perl
use CGI;
use strict;
use warnings;
my $q = new CGI;
print $q->header;
print $q->start_html;
print $q->startform('GET');
print 'What is your name? ';
print $q->textfield(-name=>'Name',
                    -default=>'John Doe',
                    -size=>'20',
                    -maxlength=>'30');
print $q->br;
print 'You entered ', $q->param('Name'), ' last time';
print $q->br;
print $q->submit;
print $q->endform;
print $q->end_html;

Pay attention to the following line:

print 'You entered ', $q->param('Name'), ' last time';

After a form is submitted, fields in it can be accessed by the param method. In this case, $q->param('Name') evaluates to the value of the text box named "Name" when this script is requested.

Note that the following line produces just a <BR /> tag:

print $q->br;

By default, a form specifies that the same script be invoked when the form is submitted. In other words, when you submit a form, it requests the same script, but supplies the field values using either the POST or GET method.

This default behavior can be changed if you specify a second parameter to the startform method. For example, if you want to invoke a script called login.cgi, do the following:

print $q->startform('POST','./login.cgi');

The . in ./login.cgi refers to the directory of the invoking script. This way, you can specify paths that are relative to an invoking script.

Copyright © 2008-05-09 by Tak Auyeung