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 comes with four functions which are quite symmetrical in form and function. Two functions, carp() and cluck(), only print out warnings, while two other functions, croak() and confess(), terminate the script and also print out a sequence of error messages. Both cluck() and confess() can also print out the stack backtrace, making it easier to pinpoint the problem.
The Carp module can be used wherever descriptive error messages warning you about potential problems are required. They're not going to make your program run any better, but they will simplify and streamline the process of error detection and recovery.
It should be noted that although, they provide much-needed information, all the Carp functions internally call warn() or die(). However, since they're very lightweight and offer numerous advantages, I'd still recommend that you use them in preference to both die() and warn().
I've rewritten the example above to demonstrate the utility of Carp.
#!/usr/bin/perl
use Carp;
sub readFile
{
my $filename = shift(@_);
open(FILE, $filename) or croak("Cannot locate file!");
print <FILE>;
close FILE;
}
readFile("dummy.txt");
And here's the output.
Cannot locate file! at ./carpdemo.pl line 8
main::readFile('dummy.txt') called at ./carpdemo.pl line 13
This article copyright Melonfire 2001. All rights reserved.