In Perl, error handling is traditionally done using the die, warn functions, and the eval block. For proper program termination, it is recommended to use die for critical errors and the warn function for warnings. Another way is to use the block operator eval to catch fatal errors for further handling.
Example:
open my $fh, '<', 'file.txt' or die "Can't open file: $! "; printf $fh "Hello" or warn "Couldn't write: $! "; # Error handling using eval my $result = eval { risky_function(); 1; }; unless ($result) { print "Error detected: $@ "; }
There are also modules like Try::Tiny and Error that implement try/catch in Perl.
What is the difference between using eval {} and the string eval "...", and what pitfalls exist for each method?
Many mistakenly believe they are identical.
eval { ... }works like a block-based try/catch, whileeval "..."compiles and executes the string as Perl code at runtime. When using the string, it is easy to make a mistake and potentially expose code to SQL injections or compilation bugs.
Example of differences:
# Compiles and executes the string as Perl code my $var = 'my $x = 2 + 2'; eval $var; # eval DIRTY! # Safe block-based version my $error = eval { die "fail"; }; print $@ if $@;
History
In one project, developers used eval "code" for dynamically generating commands, leading to unreachable syntax errors at runtime and debugging issues.
History
Incorrect error catching: exceptions thrown inside eval using local variables were not handled because $@ was overwritten by the subsequent log function call.
History
In old code, instead of using try/catch, only die() was employed, resulting in uncontrolled termination of the Perl process and data loss in database transactions.