PERL / CHAPTER 13
Exception capture and honest success signals
AdvancedUse block eval without confusing false results and failure.
By the end of this chapter
- Separate a successful falsey result from an exception
- Capture $@ promptly
- Avoid evaluating data as source
The idea
Block eval catches an exception raised by die and lets a caller inspect failure. Its return value alone can be misleading if successful work legitimately returns zero, an empty string, or undef. Use an explicit final true value inside the protected block as a success sentinel, while storing the operation’s actual result separately.
After failure, capture $@ before other operations that might disturb it. Keep the protected work narrow and choose a recovery policy that does not erase useful context. String eval compiles and executes source text and is a different tool; it should not be used merely to parse ordinary external data. Prefer structured parsing and explicit validation rather than promoting data into executable code.
use strict; use warnings;
my $value;
my $ok=eval { $value=0; 1 };
if (!$ok) { my $error=$@; die $error; }
print "success:$value\n";success:0
The final one indicates normal completion, while the legitimate zero result remains separate from the success flag.
Try it yourself
Wrap a parser so a valid zero result is preserved and an actual exception carries its original message.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING