Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by kcott (Archbishop)
on Oct 29, 2015 at 16:33 UTC ( [id://1146387]=note: print w/replies, xml ) Need Help??


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

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:

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

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

— Ken

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

    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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-23 22:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found