Re: eval without warnings



On Sep 27, Bryan R Harris said:

"2*(3+2)" ==> 10
"2*dog"  ==> "2*dog"
"mysquarefunction(2)" ==> 4
"3*mysquarefunction(2)" ==> 12
"some guy" ==> "some guy"

Here's a solution that works for the cases you've provided:

  sub try_eval {
    local $@;
    my $warning;
    local $SIG{__WARN__} = sub { $warning = 1 };
    my $expr = shift;
    my $val = eval $expr;
    $val = $expr if $@ or $warning;
    return $val;
  }

It catches fatal errors (via $@) and non-fatal warnings (via the __WARN__ handler). If there is an error or warning, the expression itself is returned; otherwise, the returned value from that expression is returned.

--
Jeff "japhy" Pinyan        %  How can we ever be the sold short or
RPI Acacia Brother #734    %  the cheated, we who for every service
http://www.perlmonks.org/  %  have long ago been overpaid?
http://princeton.pm.org/   %    -- Meister Eckhart
.



Relevant Pages

  • Re: gay and smart!
    ... He also passed on the warning not to bother us to ... the guy who took the shift after him. ... Hey, ho, what? ...
    (soc.motss)
  • Re: Could not lock file
    ... >I have a lot of users getting a warning message -2147467259, ... > these function's are launched from a timer function to compare records in ... Sub' runs in the event handler. ...
    (microsoft.public.vb.controls)
  • Re: gay and smart!
    ... He also passed on the warning not to bother us to ... the guy who took the shift after him. ... Hey, ho, what? ...
    (soc.motss)
  • Re: gay and smart!
    ... He also passed on the warning not to bother us to ... the guy who took the shift after him. ... Hey, ho, what? ...
    (soc.motss)
  • Re: gay and smart!
    ... He also passed on the warning not to bother us to ... the guy who took the shift after him. ... Hey, ho, what? ...
    (soc.motss)