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?
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.
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 withinBLOCK
at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With