The Block Form: Exception Handling

In this form, eval is followed by a block of code, not a scalar containing a string. It is used for handling run-time errors, or exceptions. Errors can be internal built-in ones (out-of-memory, divide-by-zero) or user-defined ones produced by die.

The following example shows how you can use the block form eval to trap a run-time divide-by-zero error:

eval {
$a = 10; $b = 0;
     $c = $a / $b;     # Causes a run-time error, 
                       # which is trapped by eval
};
print $@;   # Prints  "Illegal division by 0 at try.pl line 3"

When the script is compiled, Perl syntax-checks the block of code and generates code. If it encounters a run-time error, Perl skips the rest of the eval block and sets $@ to the corresponding error text.

To signal your own errors, you use die. Perl knows whether a piece of code is currently executing inside an eval, and so, when die is called, Perl simply gives the error string — die’s argument — to the global $@, and jumps to the statement following the eval block. In the following example, open_file invokes die if it has trouble opening a file. To use this function, wrap it inside an eval.

sub open_file {
    open (F, $_[0]) || die "Could not open file: $!";
}

$f = 'test.dat';
while (1) {    
    eval {
                       open_file($f);# if open_file dies, the program doesn't quit
    };
    last unless $@;     # no error: break out of the loop.
    print "$f is not present. Please enter new file name $f";
    chomp($f = <STDIN>);
}

Java/C++ programmers would of course recognize the parallel to ...

Get Advanced Perl Programming 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.