Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

eval '...'; die "err: $!"

by almr (Acolyte)
on Nov 09, 2021 at 18:26 UTC ( #11138639=perlquestion: print w/replies, xml ) Need Help??

almr has asked for the wisdom of the Perl Monks concerning the following question:

Hi, It seems concatenating to an eval-raised exception destroys it?
perl -Mstrict -we 'eval q(x=3) or die "err $!"' # actual error destroyed perl -Mstrict -we 'eval q(x=3) or die $!' # actual error printed

What's going on?

Replies are listed 'Best First'.
Re: eval '...'; die "err: $!"
by haukex (Bishop) on Nov 09, 2021 at 18:39 UTC

    The correct error variable to check after an eval is $@, not $! - the latter is actually empty in this particular case, but could potentially contain an error caused by a previous operation, leading to misleading results (try perl -Mstrict -we 'chdir("/foobarquz"); eval q(x=3) or die $!'). Also note perl -Mstrict -we 'eval q(x=3); die' has the same behavior as your second example, the reason is documented in die:

    If LIST was empty or made an empty string, and $@ already contains an exception value (typically from a previous eval), then that value is reused after appending "\t...propagated".
Re: eval '...'; die "err: $!"
by tybalt89 (Prior) on Nov 09, 2021 at 18:38 UTC

    Wrong var.

    perl -Mstrict -we 'eval q(x=3) or die "err $@"'


    err Can't modify constant item in scalar assignment at (eval 1) line 1 +, at EOF Bareword "x" not allowed while "strict subs" in use at (eval 1) line 1 +.
Re: eval '...'; die "err: $!"
by perlfan (Vicar) on Nov 10, 2021 at 11:05 UTC
    You might have cribbed that from an idiom, like: open my $fh, q{<}, $file or die $!

    Updated before haukex caught my mistake.

      A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11138639]
Approved by haukex
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2022-05-25 23:20 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (91 votes). Check out past polls.