ERROR TRAPPING IN PERL

Error trapping in Perl is handled either by checking the return value of individual function calls using an if or unless, by using “short-circuit” logic operators (and/or) or, if you think the error is severe or normally untrappable, you can embed the statement into a call to eval() and check the return value of $@. For example, to check for errors when opening a file we can do:

if (open(DATA,$file))
{
    # Do something
}
else
{
    die "Error opening $file: $!\n";
}

or

open(DATA,$file) or die "Error opening $file: $!\n";

or when checking a calculation:

$calculation = "34/0";
$result = eval($calculation);
print "Error: $@\n" if ($@);

In essence there is nothing wrong with any of these methods in Perl, but in a larger program ...

Get Perl To Python Migration 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.