Perl: be safe to use eval in modules

Perl: be safe to use eval in modules
Why?

Using the eval{} form as an exception trap in libraries does have some issues. Due to the current arguably broken state of __DIE__ hooks, you may wish not to trigger any __DIE__ hooks that user code may have installed. You can use the local $SIG{__DIE__} construct for this purpose, as this example shows:
# a private exception trap for divide-by-zero
eval { local $SIG{‘__DIE__’}; $answer = $a / $b; };
warn $@ if $@;
This is especially significant, given that __DIE__ hooks can call die again, which has the effect of changing their error messages:
# __DIE__ hooks may modify error messages
{
local $SIG{‘__DIE__’} =
sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
eval { die “foo lives here” };
print $@ if $@; # prints “bar lives here”
}
Because this promotes action at a distance, this counterintuitive behavior may be fixed in a future release.

Leave a Reply

Your email address will not be published. Required fields are marked *

16 − 11 =