I just spent a hour trying to find a bug in some code that I was eval-ing. It turns out that there was no bug in the eval code; the bug was in how I checked the result of the eval. I am posting it to the monastery since I've seen this type of bug in LOTS of Perl code before, and I never realized it was a bug until now.
First, some code:
As most people know, eval returns undef if it fails, and the value of the last operation if it succeeds. In the code above, the last operation is an argument-less return, so eval returns undef even though it succeeded. Hence, we can't check the return value to determine if an eval succeeded; we need to check $@:use strict; my $num = 1; print "Surprise!\n" if (!defined(eval { $num++; return;})); print "$num\r\n";
This gives the desired result.use strict; my $num = 1; eval { $num++; return;}; print "Surprise!\n" if ($@); print "$num\r\n";
-Ton
-----
Be bloody, bold, and resolute; laugh to scorn
The power of man...
In reply to Checking the success of eval by ton
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |