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.
Those of you who've been programming for some time know the value of error messages - they're a great way to scare the pants off clueless users. They also have other, more mundane uses, like actually helping developers track down bugs in their scripts (yeah, right!) and gracefully handling errors as and when they occur.
Perl comes with two very important and useful error-handling functions, die() and warn(). You're probably already familiar with both of these; die() is used to kill a rogue script, printing out an optional status message, while warn() is used to warn the user about possible error conditions by printing out either a user-supplied string or a default message.
Unfortunately, sometimes more descriptive errors are needed. Although die() and warn() work great for printing out errors and warnings, they don't offer this information from the perspective of the "caller" in the program. For example, when you call die() from within a function, die() will report the error from the location where it is called and not from the perspective of the called function. An example should make this clearer.
#!/usr/bin/perl
sub readFile
{
my $filename = shift(@_);
open(FILE, $filename) or die("Cannot locate file!");
print <FILE>;
close FILE;
}
readFile("dummy.txt");
If the file "dummy.txt" cannot be found, Perl will exit the script with the following error message:
Cannot locate file! at ./carpdemo.pl line 8.
What is required, therefore, is something that not only prints out the error when it happens, but also provides information on the sequence of function calls leading up to the error. Something, in short, like the Carp module.
This article copyright Melonfire 2001. All rights reserved.