Chapter 14. 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 latest version at any time from http://stein.cshl.org/WWW/software/CGI/. This book doesn’t include a complete reference for the Perl language, but if you already use Perl for CGI, you know how essential CGI.pm can be. So we include this chapter on CGI.pm as a convenience for Perl-savvy readers.

CGI.pm is an object-oriented module that 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, ...

Get Webmaster in a Nutshell, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.