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...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Checking the success of eval
by ncw (Friar) on Apr 21, 2001 at 01:55 UTC | |
by tye (Sage) on Apr 21, 2001 at 02:04 UTC | |
by ncw (Friar) on Apr 21, 2001 at 02:31 UTC | |
|
Re: Checking the success of eval
by satchboost (Scribe) on Apr 21, 2001 at 00:16 UTC | |
|
Re: Checking the success of eval
by cLive ;-) (Prior) on Apr 21, 2001 at 04:17 UTC |