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.


In reply to Re^4: Exiting eval via next: is that so bad? by haukex
in thread Exiting eval via next: is that so bad? by jplindstrom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.