CGI and Object Oriented Perl: Input
May 10, 1999
CGI and Object Oriented Perl: Input
Now, let's take a moment to consider a basic CGI example.
CGI requests are typically the result of a
form submission
the user makes from a web page. Imagine a simple HTML form
which requests a user's name and age. Suppose the HTML
below were part of a larger HTML document:
<form method=get action="/cgi-bin/process.cgi">
<input type=text name="username" width=15>
Your name?
<br>
<input type=text name="userage" width=3>
Your age?
<Br>
<input type=submit>
</form>
The above HTML would produce a page that looked something
like this:
When the user submits this page, the values entered in the
input fields are passed to the program specified in
the ACTION attribute of the <FORM> tag; in this case,
that is the URL "/cgi-bin/process.cgi". This
program -- "process.cgi" -- would be the filename
of our Perl program.
Let's turn back to Perl -- we know how to request the CGI
module, so let's begin using the CGI object to read
the data submitted by the web surfer. Example first,
explanation follows:
process.cgi
#!/usr/bin/perl
use CGI;
#create an instance of the CGI object
$cgiobject = new CGI;
#grab the values submitted by the user
$name=$cgiobject->param("username");
$age=$cgiobject->param("age");
Once again, we start the program by requesting the CGI module.
That done, we need to create an instance
of the CGI object. Think of the module as containing a template
for the CGI object -- we do not use the template
directly, but rather stamp out our own copy of the object
from the template. This is done using the new
constructor; as you can see, we use a scalar variable,
$cgiobject, and assign to it a new instance of the CGI object.
From here on in, we access the CGI object through its
instance, $cgiobject.
In the next two lines of code we pluck the data from the
form submission. Since this Perl program is written
with this particular HTML page in mind, it knows that the
two values of interest are the user's name and age. To
retrieve the user's name, we setup a scalar variable,
$name, and assign to it the result of the param action
of the CGI object. When an object possesses an action,
which is essentially a function that lives inside the object,
it is known as a method (jargon, jargon!). Notice
the syntax:
$Perl_Variable=$CGI_Object->methodName(parameters);
Translated into some type of English, we can say that $name
is assigned the value of the parameter "username"
from the CGI object. What is "username"? Recall
our HTML form, in which we named the input box for the
user's name "username". This is the name of that
input box as passed via CGI.
Once the user's name has been placed into $name, we then
pluck another piece of data, the value of the HTML
form field "userage", and assign its value to
the Perl variable $age.
Notes on Running CGI
The Perl You Need to Know
CGI and Object Oriented Perl: Output
|