Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Drawback of eval {---}if ($@){---}, when using many times?

by rajuskark (Acolyte)
on Oct 29, 2015 at 11:40 UTC ( #1146365=perlquestion: print w/replies, xml ) Need Help??

rajuskark has asked for the wisdom of the Perl Monks concerning the following question:

I am using eval block many time in my program is. I want to know is there any harm or any drawbacks if using it many times

while (){ ---- eval{----};if($@){-----} ---- eval{----};if($@){-----} --- eval{----};if($@){-----} ----- ----- eval{----};if($@){-----} ----- #and so on }

Original content restored by GrandFather

Replies are listed 'Best First'.
Re: Drawback of eval {---}if ($@){---}, when using many times?
by Corion (Patriarch) on Oct 29, 2015 at 11:52 UTC

    You could wrap that pattern in a subroutine if the error code is always the same:

    sub perform { my( $code )= @_; eval { $code->() }; if( $@ ) { ... # error handling }; }; while() { perform(sub{ # connect-to-database }); perform(sub{ # munge-data }); perform(sub{ # write-report }); }

    Also see Try::Tiny.

    The only drawback of using eval {} over not using it is that each eval { ... } is a tiny bit slower than the code without it. If you are doing anything else in your code, that slowdown is usually not worth optimizing away.

      Yes, but!

      sub perform { my $code = shift; my $result = eval { $code->(@_) }; if( $@ ) { ... # error handling } else { return $result; } };

      looks more flexible to me, since that way you can pass arguments for the subs to the dispatcher (e.g. error displayed), and you get something back for so much carefulness.

      update: This is a good example for following the DRY principle - Don't Repeat Yourself.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Re: Drawback of eval {---}if ($@){---}, when using many times?
by kcott (Archbishop) on Oct 29, 2015 at 16:33 UTC

    G'day rajuskark,

    "I am using eval block many time in my program is. I want to know is there any harm or any drawbacks if using it many times"

    There are drawbacks to using eval that are not related to the number of times it is used. See

    Whether these drawbacks apply to your code will depend on what all the various '----'s are, as well as whatever code surrounds your while loop. As none of that is shown, you'll need to determine this for yourself.

    Your use of multiple 'eval{----};if($@){-----}' looks clunky and may be entirely unnecessary; that is, you may be able to use just one 'eval{----};if($@){-----}'. Here's a sample script to show how that might be achieved.

    #!/usr/bin/env perl use strict; use warnings; use autodie; my @ids = 0 .. 3; while () { eval { my $id = pop @ids; die $id if $id; open my $fh, '<', 'pm_1146365_nonexistent_file'; }; warn "TRAPPED: $@" if $@; last unless @ids; }

    When run, this produces:

    $ TRAPPED: 3 at ./ line 12. TRAPPED: 2 at ./ line 12. TRAPPED: 1 at ./ line 12. TRAPPED: Can't open 'pm_1146365_nonexistent_file' for reading: 'No suc +h file or directory' at ./ line 13

    See also: the autodie pragma and the croak and confess functions of the Carp module.

    — Ken

      I've made this a question, please see Do the Monks recommend Try::Tiny for eval work?.

      There's been a bunch of talk about the if $@ after eval lately. Do the monks who have much experience with eval recommend Try::Tiny, or do they just use something like Corion suggested in Re: What does eval actually do?? Some of my modules and especially their unit tests are using the 'faulty' method, and it's blatantly clear I may have unknown issues.
Re: Drawback of eval {---}if ($@){---}, when using many times?
by Your Mother (Archbishop) on Oct 29, 2015 at 15:07 UTC

    if($@) can be a problem on its own: Try::Tiny#BACKGROUND.

Re: Drawback of eval {---}if ($@){---}, when using many times?
by GotToBTru (Prior) on Oct 29, 2015 at 12:25 UTC

    It looks clunky, I am not sure if there is anything wrong with it. The danger with eval is if you have variable interpolations that may allow uncontrolled code to be run.

    If the blocks in the eval look similar then you might want to replace them with a subroutine call.

    Dum Spiro Spero
Re: Drawback of eval {---}if ($@){---}, when using many times?
by Athanasius (Archbishop) on Oct 30, 2015 at 12:42 UTC

    Hello rajuskark,

    If you have a third-party subroutine sub foo which throws an exception on failure, and you want to handle the exception and allow the code to continue in its normal path, then you have to use either eval or a suitable module — such as Try::Tiny or TryCatch — to catch the exception. I think the other monks who’ve posted in this thread have assumed that this is the case for your code, and given you excellent advice based on that assumption.

    But I can’t help suspecting that your proposed design is in fact using die and eval in place of normal flow control. If so, this is wrong. A subroutine which may fail as part of normal script execution should indicate the failure by returning a suitable value, not by calling die. A common convention is to return undef on this kind of failure, and a true value (usually 1) on success. An exception should be thrown (via die) only in a situation which is — well, exceptional. :-) That is, a catastrophic failure which is likely to derail the script’s normal logical flow. In other words, exception handling should never be deployed as a substitute for normal flow control.

    To illustrate this point, consider the following benchmark code which compares the efficiency of two empty subroutines: one which indicates failure by throwing an exception, and one which instead just returns undef:

    Admittedly, this is a rather silly benchmark, as the two subs do nothing. But it does show that exception handling is, in isolation, of the order of 30 times less efficient than normal flow control. Which isn’t a problem when it’s used correctly, precisely because exceptions are intended to be thrown and caught only occasionally (if at all) during the runtime of a program.

    From the Camel Book (4th Edition, 2012, p. 320):

    Under extraordinary circumstances you might choose to raise an exception to indicate an error. Use this measure sparingly, though; otherwise, your whole program will be littered with exception handlers.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Drawback of eval {---}if ($@){---}, when using many times?
by Anonymous Monk on Oct 29, 2015 at 11:46 UTC


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1146365]
Front-paged by tye
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2023-10-03 05:17 GMT
Find Nodes?
    Voting Booth?

    No recent polls found