Perl exception handling

I saw that at the end of eval blocks for exception handling in perl appears 1. Why is this required? What happens if the eval block returns false?

Is this required even if we do not directly use $@ , but some library from CPAN to handle exceptions?

+4
source share
2 answers

What happens if the eval block returns false?

This false value is returned by eval .

Why is this required?

This is not required.

 my $foo = eval { foo() }; 

great if you're ok with $foo being undef on exception.

What you saw

 if (!eval { foo(); 1 }) { ... } 

The code returns true so that if knows that eval succeeds. eval will return false for an exception.

+6
source

To expand on ikegami's answer: most people write code as follows:

 eval { might_throw_exception() }; if ( $@ ) { ... } 

This is not pre-5.14 true, because $@ may not be the true value, even if an exception was thrown due to overwriting the destructor or other factors. return 1 - workaround; see Try :: Tiny for a full explanation.

0
source

All Articles