Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 715
null Avatar asked Dec 20 '22 05:12

null


2 Answers

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.

like image 99
Dave Sherohman Avatar answered Jan 19 '23 00:01

Dave Sherohman


You could write above eval like,

my $result = eval {
    # here is put some code that may throw exception
    1;  # Why is the "1;" here ?
};

In this case $result will be 1 only if there was no exception inside eval, and undef otherwise.

So in this particular case 1 ensures that or do {..} doesn't get executed if there was no exception.

if ($@) {..} is perhaps more idiomatic way to do the same thing, and $@ is always set when eval{..} fails.

like image 41
mpapec Avatar answered Jan 19 '23 01:01

mpapec