Jun/092
use autodie;
When writing perl code you’ll often find yourself using built-in functions that do not throw a fatal error when there is a problem. Instead you are expected to check the return value of the function, and if it is false, call die() yourself. Consider the following code:
This is a very cumbersome way to write code as you could easily forget to add these extra checks. If you’re lazy, which you should be, you’ll want fatal errors without having to write a bunch of extra code. This is where autodie steps in. The above code can then be rewritten as:
Much better. Generally you should want anything that has an unexpected problem to throw a fatal error. If you want your code to catch the error, handle it, and possibly continue running, wrap the offending code in an eval:
On a side note: block evals, such as eval{ print ‘hi!’; } are very efficient and you can use them liberally. String evals, such as eval(”print ‘hi!’”), are not nearly as efficient and should be avoided.
Leave a comment
No trackbacks yet.

8:39 am on June 30th, 2009
Your eval version can be a little cleaner:
my $file = “testfile.txt”;
eval {
open my $fh, “>”, $file;
print {$fh} “Hello world!\n”;
close $fh;
} or {
warn $@;
unlink $file if -e $file;
exit 255;
}
Since close will return true if it succeeds, we can use that return to build a try/catch like system that is not dependent on $@ (which could be changed by an errant DESTROY method that failed to localize it). Also, warning about the error means that if the unlink fails it won’t mask the error from the eval.
3:43 am on July 20th, 2009
Chas.Owens, you forgot
after that
:)
unlink(’testfile.txt’) if -e ‘testfile.txt’; is a race condition, testfile.txt could exist when -e ‘testfile.txt’; is called, but be deleted before unlink is called.
Not to worry, since autodie and $fh are lexically scoped, you could simply write
eval {
open( my $fh, '<', 'testfile.txt' );
print $fh "Hello world!\n";
1;
} or do {
no autodie 'unlink';
unlink 'testfile.txt';
die;
};
or
eval {
use autodie;
open( my $fh, '<', $file );
print $fh "Hello world!\n";
1;
} or do {
unlink $file;
die
};