Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Perl's $@ ever be undefined after an eval?

Tags:

perl

eval

I'm working on the "Error Handling and Reporting" chapter of Mastering Perl. In perlvar's entry for $@, it says:

The Perl syntax error message from the last eval() operator. If $@ is the null string, the last eval() parsed and executed correctly (although the operations you invoked may have failed in the normal fashion).

Now I'm wondering when an eval might not execute correctly, leaving $@ with an undefined value. Are there any such cases?

like image 344
brian d foy Avatar asked Jul 21 '13 19:07

brian d foy


2 Answers

Here's one way to do it (but sit down before you read it. ;))

$@ = 123;
eval q{
  $@ = 456;
  print ">>>$@<<<\n";
  goto SKIP;
};

SKIP:
print ">>>$@<<<\n";
like image 158
shawnhcorey Avatar answered Sep 28 '22 02:09

shawnhcorey


The BACKGROUND section of the Try::Tiny docs contain some info on how $@ can be clobbered and why Try::Tiny takes special care to avoid clobberage, and always tests the return value of eval rather than testing $@ for truth. All of them are in there because someone ran into them at some point, but I think that the eval-in-DESTROY scenario is the one most likely to trip someone up. Basically, if die causes some object to go out of scope, and that object has a DESTROY that calls eval, then the value that you died with to begin with is irretrievably lost. Assuming the eval in the DESTROY doesn't throw an error, $@ will be "" following the outer eval.

like image 24
hobbs Avatar answered Sep 28 '22 03:09

hobbs