in reply to Re^3: Exiting eval via next: is that so bad?
in thread Exiting eval via next: is that so bad?
Now imagine several more "verify" type calls within that same eval.
Yeah, I figured it was something like that. Personally I still wouldn't use that "eval/die with a fixed string" pattern, and instead maybe wrap each call in an eval, or to make it look a little nicer, perhaps Try::Tiny. Of course, this being Perl, other ways come to mind :-) Say you've got a bunch of verify_* functions that you can't change and whose errors are fatal, but you want nonfatal versions of them:
use warnings; use strict; # UUT use Scalar::Util qw/looks_like_number/; sub verify_number { my ($arg) = @_; die "not a number" if !defined $arg; looks_like_number($arg) or die "not a number"; return; } # wrap the funcs my @funcs = qw/ verify_number /; for my $f (@funcs) { my $orig = \&{$f}; my $wrapped = sub { eval { $orig->(@_); 1 } }; { no strict 'refs'; *{$f.'_nf'} = $wrapped } } use Test::More tests => 4; # helper sub exception (&) { eval { shift->(); 1 } ? undef : ($@ || die "\$@ was false") } ok !exception { verify_number("3.14") }; like exception { verify_number("foo") }, qr/\bnot a number\b/i; ok verify_number_nf("3.14"); ok !verify_number_nf("foo");
Of course you don't need to install the wrapped versions into the symbol table, a hash would work fine too.
|
|---|