Next: Objects Oriented Programming
Up: Form processing
Previous: Web servers
Contents
Index
Constructing a CGI script using Perl is made enormously
easier through use of the CGI module. This module
can be used in a script as
use CGI qw(:common);
which imports into your script a whole range of routines
useful in a CGI environment. The CGI.pm documentation
contains a description of all the available routines, and
you should consult this for details. Generally
such routines fall into two classes:
- HTML shortcuts: Such routines are handy for
generating common html constructions. For example,
there is a routine h3('A level 3 heading') which
will return the string <h3>A level 3 heading</h3> used
to render a level 3 heading.
- parameter processing: These routines are used to
check for values of available form elements, and retrieve
those values if present. The main routine in this
context is param(), used as my $sin = param('id'),
which gets the value of the form element with name id and
assigns it to the Perl variable $sin.
Here's a simple example taken from the CGI distribution of
a script which asks you to fill in some values, and when the
submit button is pressed, prints out to the screen
the values entered. Note that the first line of the
script,
#!C:/Perl/bin/perl
gives the location of the program to be used to run the
script.
#!C:/Perl/bin/perl
use CGI ':standard';
print header;
print start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your name? ",textfield('name'),
p,
"What's the combination?",
p,
checkbox_group(-name=>'words',
-values=>['eenie','meenie','minie','moe'],
-defaults=>['eenie','minie']),
p,
"What's your favorite color? ",
popup_menu(-name=>'color',
-values=>['red','green','blue','chartreuse']),
p,
submit,
end_form,
hr;
if (param()) {
print
"Your name is: ",em(param('name')),
p,
"The keywords are: ",em(join(", ",param('words'))),
p,
"Your favorite color is: ",em(param('color')),
hr;
}
print a({href=>'../cgi_docs.html'},'Go to the documentation');
print end_html;
To run this program, save it as, for example, tryme.cgi
under the directory specified
with the ScriptAlias directive in the httpd.conf
file, and then go to http://localhost/cgi-bin/tryme.cgi.
Next: Objects Oriented Programming
Up: Form processing
Previous: Web servers
Contents
Index