Reputation: 263
I have seen a 1 appear at the end of eval blocks for exception handling in perl. Why is that required? What happens if an eval block returns false?
Is this required even if we dont use $@ directly but some library from CPAN to do exception handling?
Upvotes: 4
Views: 732
Reputation: 50274
To expand on ikegami's answer: most people write code like this:
eval { might_throw_exception() };
if ($@) { ... }
This is wrong pre-5.14, because $@
may not be a true value even if an exception was thrown due to a destructor overwriting it, or other factors. return 1
is a workaround; see Try::Tiny for a full explanation.
Upvotes: 0
Reputation: 385496
That false value is returned by eval
.
It's not required.
my $foo = eval { foo() };
is perfectly fine if you're ok with $foo
being undef on exception.
What you've seen is
if (!eval { foo(); 1 }) {
...
}
The code is returning true to let the if
know the eval
succeeded. eval
will return false on exception.
Upvotes: 6