Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by Corion (Patriarch)
on Oct 29, 2015 at 11:52 UTC ( [id://1146368]=note: print w/replies, xml ) Need Help??


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

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.

Replies are listed 'Best First'.
Re^2: Drawback of eval {---}if ($@){---}, when using many times?
by shmem (Chancellor) on Oct 29, 2015 at 13:47 UTC

    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'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1146368]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-16 07:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found