30
Jun/09
2

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:

open( my $fh, '>', 'testfile.txt' )
    or die('Unable to open testfile.txt for write');
print $fh "Hello world!\n";
close( $fh )
    or die('Unable to close testfile.txt');

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:

use autodie;

open( my $fh, '>', 'testfile.txt' );
print $fh "Hello world!\n";
close( $fh );

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:

use autodie;

eval{
    open( my $fh, '>', 'testfile.txt' );
    print $fh "Hello world!\n";
    close( $fh );
};
if ($@) {
    unlink('testfile.txt') if -e 'testfile.txt';
    die($@);
}

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.

Tagged as: