Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by almr (Sexton)
on Nov 09, 2021 at 18:26 UTC ( [id://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 (Archbishop) 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 (Monsignor) on Nov 09, 2021 at 18:38 UTC

    Wrong var.

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

    Outputs:

    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.