home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl in a Nutshell

Perl in a NutshellSearch this book
Previous: 9.4 CGI Environment Variables Chapter 10 Next: 10.2 Importing Method Groups
 

10. The CGI.pm Module

CGI.pm is a Perl module for creating and parsing CGI forms. It is distributed with core Perl as of Perl 5.004, but you can also retrieve CGI.pm from CPAN, and you can get the very latest version at any time from ftp://ftp-hygenome.wi.mit.edu/pub/software/WWW/ .

CGI is an object-oriented module. Don't let the object-oriented nature scare you off, though; CGI.pm is very easy to use, as evidenced by its overwhelming popularity among all levels of Perl programmers. To give you an idea of how easy it is to use CGI.pm, let's take a scenario in which a user fills out and submits a form containing her birthday. Without CGI.pm, the script would have to translate the URL-encoded input by hand (probably using a series of regular expressions) and assign it to a variable. For example, you might try something like this:

#!/usr/bin/perl 
# cgi script without CGI.pm

$size_of_form_info = $ENV{'CONTENT_LENGTH'};
read ($STDIN, $form_info, $size_of_form_info);

# Split up each pair of key=value pairs
foreach $pair (split (/&/, $form_info)) {

   # For each pair, split into $key and $value variables
   ($key, $value) = split (/=/, $pair);

   # Get rid of the pesky %xx encodings
   $key =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
   $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;

   # Use $key as index for $parameters hash, $value as value
   $parameters{$key} = $value;
}

# Print out the obligatory content-type line
print "Content-type: text/plain\n\n";

# Tell the user what they said
print "Your birthday is on " . $parameters{birthday} . ".\n";
Regardless of whether this code actually works, you must admit it's ugly. With CGI.pm, the script could be written:
#!/usr/bin/perl -w
# cgi script with CGI.pm

use CGI;

$query = CGI::new();
$bday = $query->param("birthday");
print $query->header();
print $query->p("Your birthday is $bday.");
Even for this tiny program, you can see that CGI.pm can alleviate many of the headaches associated with CGI programming.

As with any Perl module, the first thing you do is call the module with use . You then call the constructor ( new() ), creating a new CGI object called $query . Next, get the value of the birthday parameter from the CGI program using the param method. Note that CGI.pm does all the work of determining whether the CGI program is being called by the GET or POST methods, and it also does all the URL decoding for you. To generate output, use the header method to return the content type header, and the p method to generate a paragraph marker <P> tag.

However, this is only the tip of the iceberg as far as what CGI.pm can do for you. There are three basic categories of CGI.pm methods: CGI handling, creating forms, and retrieving environment variables. (A fourth category is creating HTML tags, but we don't cover those in detail.) Table 10.1 lists most of these methods. They are also covered in more detail later in this chapter.


Table 10.1: CGI.pm Methods
CGI Handling
keywords Gets keywords from an <ISINDEX> search.
param Gets (or sets) the value of parameters.
append Appends to a parameter.
import_names Imports variables into a namespace.
delete Deletes a parameter.
delete_all Deletes all parameters.
save Saves all parameters to a file.
self_url Creates self-referencing URL.
url Gets URL of current script without query information.
header Creates HTTP header.
redirect Creates redirection header.
cookie Gets (or sets) a cookie.
nph Declares this to be a NPH script.
dump Prints all name/value pairs.
Form Generation
start_html Generates an <HTML> tag.
end_html Generates an </HTML> tag.
autoEscape Sets whether to use automatic escaping.
isindex Generates an <ISINDEX> tag.
startform Generates a <FORM> tag.
start_multipart_form Generates a <FORM> tag for multipart/ form-data encoding.
textfield Generates an <INPUT TYPE=TEXT> tag.
textarea Generates an <TEXTAREA> tag.
password_field Generates an <INPUT TYPE=PASSWORD> tag.
filefield Generates an <INPUT TYPE=FILE> tag.
popup_menu Generates a popup menu via <SELECT SIZE=1> and <OPTION> tags.
scrolling_list Generates a scrolling list via <SELECT> and <OPTION> tags.
checkbox_group Generates a group of checkboxes via multiple <INPUT TYPE=CHECKBOX> tags.
checkbox Generates a single checkbox via a <INPUT TYPE=CHECKBOX> tag.
radio_group Generates a group of radio buttons via <INPUT TYPE=RADIO> tags.
submit Generates a <SUBMIT> tag.
reset Generates a <RESET> tag.
defaults Generates a <DEFAULTS> tag.
hidden Generates an <INPUT TYPE=HIDDEN> tag.
image_button Generates a clickable image button via a <SELECT> tag.
button Generates a JavaScript button.
Handling Environment Variables
accept Gets accept types from ACCEPT header.
user_agent Gets value of USER_AGENT header.
path_info Gets value of EXTRA_PATH_INFO header.
path_translated Gets value of PATH_TRANSLATED header.
remote_host Gets value of REMOTE_HOST header.
raw_cookie Gets value of HTTP_COOKIE header.
script_name Gets value of SCRIPT_NAME header.
referer Gets value of REFERER header.
auth_type Gets value of AUTH_TYPE header.
remote_user Gets value of REMOTE_USER header.
user_name Gets user name (not via headers).
request_method Gets value of REQUEST_METHOD header.

Each of these methods is covered later in this chapter, in alphabetical order.

10.1 HTML Tag Generation

In addition to the form-generation methods, CGI.pm also includes a group of methods for creating HTML tags. The names of the HTML tag methods generally follow the HTML tag name (e.g., p for <P> ) and take named parameters that are assumed to be valid attributes for the tag (e.g., img(src=>'camel.gif') becomes <IMG SRC="camel.gif"> ). We do not list all tags in this book; see the CGI.pm manpage for more information, or the book Official Guide to Programming with CGI.pm by Lincoln Stein (John Wiley & Sons, 1998).