Wicked Cool Perl Scripts | Page 3 | WebReference

Wicked Cool Perl Scripts | Page 3

[previous] [next]

Wicked Cool Perl Scripts
[This chapter is excerpted from the book, Wicked Cool Perl Scripts, 2nd Edition, authored by Steve Oualline. Copyright 2006 No Starch Press, February 2006.]

Printing Debugging Information

CGI programming requires different skills. Not only do you have to know Perl programming, but also HTML and HTML forms. Sometimes what's in the form and what you think is in the form differ. As a result, the inputs to your CGI program aren't what it expects and the program fails.

To help locate errors, it's nice to know the exact inputs to a program. This shows the use of a debug function that prints out all the CGI and environment parameters, giving the programmer a lot of extremely useful debugging information.

The Code

Using the Function

To use the function, simply put it in your CGI program and call it.

The Results

Here's the result of running the script. The form we filled in to get to this script took two parameters, a width and a height. From the debug output you can see the values we filled in. You can also see all the environment information passed to us by the CGI system.

The results

How It Works

The script uses the Parse_CGI function to grab all the CGI parameters. These are stored in the hash %form_hash:

The hash creates a

mapping. But there is a problem. Some form elements, like a multiple-selection list, can have more than one value. In that case the "value" returned is not a real value but instead a reference to an array of values.

In order to print things, your code needs to know the difference between the two. This is done using the ref function. If you have an array reference, you print the elements. If you have something else, you just print the value:

The environment is printed using a similar system. Since you don't have to worry about multiple values this time, the printing is a bit simpler:

Between the environment and the CGI parameters, you've printed every input to a CGI program.

Hacking the Script

In the field, it would be nice to be able to turn on and off the debugging output at will. One technique is use a remote shell on the server to create a file such as /tmp/cgi_debug and, if it is present, turn on the debugging.

The debug function can also be augmented to print out more information, such as the state of program variables or the contents of information files.

Printing information to the screen is one of the more useful ways of getting debugging information out of a CGI system.

[previous] [next]