Debugging Perl CGI Scripts
From Dev411: The Code Wiki
When debugging a Perl CGI script on a web server it is useful to get as much information as possible to pinpoint where the error is. When there is an error in the Perl script, often times a webserver will respond with a generic HTTP 500 - Internal Server Error which isn't very useful. More information is needed to debug this your self and especially when you are posting to a message board for assistance. Use the following tips to get better error messages:
| Table of contents |
General Techniques
Code Isolation
One of the most useful general purpose techniques for debugging an unknown error is to isolate the code you are testing. You can do this by commenting out bits of code until the program works. When it does, your last edit was causing an error.
HTTP 500 - Internal Server Error
Web servers generally provide ambiguous error messages. Any one of the following techniques will get you better information on your error. Choose which one suits you best or use a combination.
Use CGI::Carp
CGI::Carp is designed to provide better error messages when writing CGI. By default, most web servers direct STDERR to the web server's error log. When debugging CGI it may be convenient to redirect the error messages to the browser (STDOUT). Adding the following line will direct fatal (die, confess) errors to the browser:
use CGI::Carp qw/fatalsToBrowser/;
CGI::Carp also has the ability to display warning messages to the browser with the warningsToBrowser subroutine.
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
Unlike fatalsToBrowser which prevents your CGI script from running, warnings still allow your program to run. To prevent warning messages from showing up where you don't want, you can turn on and off warningsToBrowser through your script (example from cpan.org):
warningsToBrowser(0); # disable warnings print "<script type=\"text/javascript\"></script>\n"; warningsToBrowser(1); # re-enable warnings
CGI::Carp can also be used to redirect STDERR from the web server's error log to another, an application specific, one.
Read the server error log
You can, of course, always check the web server's error log for more detailed error and warning messages.
Run script from command line
To test some aspects of your script, you can also run your script from the command line. CGI.pm allows you to pass in parameters on the command line as if they were GET or POST parameters:
-sh$ perl test.cgi title="My Title" action=edit
# In test.cgi
#!/usr/bin/perl
use strict;
use CGI;
my $q = CGI->new;
print 'Title: '.$q->param('title')."\n";
print 'Action: '.$q->param('action')."\n";
Further Reading / External Links
- CGI::Carp (cpan.org) (http://search.cpan.org/~lds/CGI.pm-3.11/CGI/Carp.pm)
