One of the nice things about Perl is the huge amount of free codeout there. Available in the form of modules, this code can simplify manycommon tasks while simultaneously offering a powerful toolkit for theexperienced developer. In this article, learn about two of the most popularPerl modules: DBI, used for database connectivity, and Carp, used tosimplify error handling.
The Carp module also comes with a bunch of additional features designed specifically for use in Perl CGI scripts. These features make it easier to track errors thrown up by your CGI scripts, and to log these errors appropriately.
When running as a CGI script, your error output is automatically redirected to the HTTP server error log. Unfortunately, the output is not time-stamped, making it difficult to figure out when the error occurred. To get time-stamped error and warning messages, simply replace the line
The rest of your code remains the same.
Another nifty little feature here is the ability to echo error messages (though not warnings) to the client browser. Simply import the fatalsToBrowser() subroutine and this will be done for you automagically. Change the line
use CGI::Carp qw(fatalsToBrowser);
Now, not only will errors be recorded in the log, but they will also be displayed to the user. This may or may not be something you want (do you really want the world to see the error messages your shoddy little script vomits out?), which is why it has to be turned on manually by importing fatalsToBrowser().
Finally, the carpout() function allows you to redirect error messages to a file of your choosing, rather than sending them to the standard error log. This can be a great help while debugging, since you won't have to wade through miles of log file messages in order to find the hairballs you script coughed up.
Here's an example:
use CGI::Carp qw(carpout);
open (CARPLOG, ">>/usr/home/luser/my-script.log") or die ("Can't open log
As you can see, carpout() has to be specially imported in before it can be used. carpout() needs just one parameter, the file handle of the user-defined error log.
Keep in mind that carpout() degrades performance and should not be used in an actual production script. Use it only as a tool for debugging your script, or as an excuse to explain why it's so slow.
This article copyright Melonfire 2001. All rights reserved.