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

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to