Mike Gossland's Perl Tutorial Course for Windows


Intro to GET | CGI Module | Handling Forms | Form Errors | Fatal Errors


Chapter 6. The CGI Module

The CGI Module, CGI.pm

The CGI module, introduced quietly in the last example is a superb module for dealing with the CGI interface.

CGI.pm does everything you need to read user input, create forms, handle cookies, handle redirection, and more. It is a very useful module indeed and it is a standard module supplied with your Perl installation.

Let's examine another script just a bit more advanced than the previous one. This next script does everything in the previous script, but it also prints out any input parameters supplied to the script through either GET or POST.

Try saving this script as getpost.pl and running it in your browser window.

use CGI;

$cgi = new CGI;

for $key ( $cgi->param() ) {
    $input{$key} = $cgi->param($key);
}

print qq{Content-type: text/html

<html><head></head><body>
};

foreach $key (sort (keys %ENV)) {
    print $key, ' = ', $ENV{$key}, "<br>\n";
}

for $key ( keys %input ) {
    print $key, ' = ', $input{$key}, "<br>\n";
}

print qq{<form METHOD=POST><input type="submit" value="Post Request">
<input name="postfield"></form>};

print qq{<form METHOD=GET ><input type="submit" value="Get  Request ">
<input name="getfield" ></form>};

print qq{</body></html>};

The first line "use CGI;" calls the CGI.pm module into your perl script so you can use its features. The very first thing you need to do is to create your brand new shiny $cgi variable, which you do with $cgi = new CGI;. (For those of you who want to know, you have just entered into an object-oriented aspect of Perl, but don't be afraid. It doesn't get particularly complicated.)

As soon as you have defined this new $cgi variable, all kinds of things are available to you. For instance the first thing you see is 

for $key ( $cgi->param() ) {
     $input{$key} = $cgi->param($key);
}

Now $cgi->param() is a hash of all the (name,value) pairs that were submitted to the form. I like to assign the $cgi->param() hash to the hash "%input" even though it's a duplication of memory, because %input turns out to be easier to work with.

Next we print out the regular Content-type header and get into the html body. Then we work through all the keys in the environment hash, ENV, and print all its (key, value) pairs to the browser.

Lastly, we print out the %input hash. You'll see any values you submit appear here, already neatly parsed into (name,value) pairs. And nice to know, it doesn't matter whether that data came in as the result of a POST or a GET method. Either way, the data are there and accessible in the same way.

Now you've seen how to get at the input fields, let's see a more realistic example in practice.