nslntmnx nslntmnx - 5 months ago 10
Perl Question

What changes, if any, are required to make the following Perl eval bullet proof?

eval {
# here is put some code that may throw exception
return 1;
} or do {
my $error = $@;
# Handle error.
};



  1. Does the following style protect against $@ not being set
    correctly ?

  2. What does the following "1;" protect against?

  3. Is the "or do{" better than the saying "if ($@){ " ? If so, why?


Answer

See the Try::Tiny documentation for discussion of the things that can go wrong when using eval as a try-type statement, how they can be avoided, and why your posted code ends with 1 (to ensure the eval block returns a true value if it completes successfully).

After reading it, consider using Try::Tiny instead of going through all the gyrations of making sure each of your evals will function correctly as a try. Laziness is the first great virtue of a programmer, after all.

Comments