CGI::Carp

use CGI::Carp;
warn "This is a complaint";     # Stamp it with progname and date.
die "But this one is serious";  # But don't cause server 500 errors.

use CGI::Carp qw(carpout);      # Import this function.
open(LOG, ">>/var/tmp/mycgi-log")
    or die "Can't append to mycgi-log: $!\n";
carpout(*LOG);                  # Now uses program-specific errlog.

use CGI::Carp qw(fatalsToBrowser);
die "Fatal error messages are now sent to browser, too";

The CGI::Carp module provides versions of the warn and die Perl built-in functions, plus the Carp module's carp, cluck, confess, and croak functions which are more verbose and safer, too. They're more verbose because each message includes the date and time with the name of the program issuing the message, which helps when you're using a log file shared by a hundred different programs scribbling a thousand different messages on it at the same time.

The module is also kinder to web surfers, since premature death in a CGI script tends to cause inscrutable "Server 500" errors when the proper HTTP header doesn't get out to the server before your program pegs out, and this module makes sure that doesn't happen. The carpout function redirects all warnings and errors to the filehandle specified. The fatalsToBrowser directive sends a copy of such messages to the user's browser, too. These facilities ease debugging of problems in CGI scripts.

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.