Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice in case something goes wrong in Perl code? [duplicate]

Possible Duplicates:
How can I cleanly handle error checking in Perl?
What’s broken about exceptions in Perl?

I saw code which works like this:

do_something($param) || warn "something went wrong\n";

and I also saw code like this:

eval {
  do_something_else($param);
};
if($@) {
  warn "something went wrong\n";
}

Should I use eval/die in all my subroutines? Should I write all my code based on stuff returned from subroutines? Isn't eval'ing the code ( over and over ) gonna slow me down?

like image 957
Geo Avatar asked Nov 28 '22 03:11

Geo


2 Answers

Block eval isn't string eval, so no, it's not slow. Using it is definitely recommended.

There are a few annoying subtleties to the way it works though (mostly annoying side-effects of the fact that $@ is a global variable), so consider using Try::Tiny instead of memorizing all of the little tricks that you need to use eval defensively.

like image 132
hobbs Avatar answered Dec 21 '22 11:12

hobbs


do_something($param) || warn "something went wrong\n";

In this case, do_something is expected to return an error code if something goes wrong. Either it can't die or if it does, it is a really unusual situation.

eval {
  do_something_else($param);
};
if($@) {
  warn "something went wrong\n";
}

Here, the assumption is that the only mechanism by which do_something_else communicates something going wrong is by throwing exceptions.

If do_something_else throws exceptions in truly exceptional situations and returns an error value in some others, you should also check its return value.

Using the block form of eval does not cause extra compilation at run time so there are no serious performance drawbacks:

In the second form, the code within the BLOCK is parsed only once--at the same time the code surrounding the eval itself was parsed--and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first (see below), while also providing the benefit of checking the code within BLOCK at compile time.

like image 33
Sinan Ünür Avatar answered Dec 21 '22 12:12

Sinan Ünür