Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: eval failure does not set $@

by perl-diddler (Chaplain)
on Jun 06, 2018 at 20:30 UTC ( [id://1216055]=note: print w/replies, xml ) Need Help??


in reply to eval failure does not set $@

eval sets "$@" with the output of what you'd normally see perl output if there were errors compiling your program.

perl normally wouldn't display runtime errors if a subroutine doesn't do what it is supposed to do.

eval won't either.

If the routines you are running return a status, then you want to catch that status coming back from eval:

my $status = eval "3+4";

$status should be '7'. Only if the code you are executing "dies" or throws a warning, in the perl sense, would eval return something in $@.

Does that help?

Replies are listed 'Best First'.
Re^2: eval failure does not set $@
by haukex (Archbishop) on Jun 06, 2018 at 20:51 UTC
    Only if the code you are executing "dies" or throws a warning, in the perl sense, would eval return something in $@.

    But as I wrote, there are cases where the code in the eval can die, and $@ doesn't get set (Update: or to be more specific, gets clobbered so that it's no longer available after the eval). A simple demo of this bug:

    use warnings; use strict; sub Foo::DESTROY { eval {} } eval { for (bless {}, "Foo") { print "Hello"; die "KABOOM"; } }; print "<$@>\n"; # Where's the kaboom? There was supposed # to be an earth-shattering kaboom!

    Even on Perl 5.26, this only prints "Hello<>". That's why the eval { ...; 1 } or do { ... }; pattern is better - choroba showed how that pattern still works even in the presence of a similar bug on Perls <5.14 here.

    If the routines you are running return a status, then you want to catch that status coming back from eval

    I would suggest writing it this way, where of course 3+4 is a stand-in for something more complex (and it may also be a false value):

    my $status; eval '$status = 3+4; 1' or warn $@||"unknown error";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1216055]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-25 05:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found