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'