sdetweil has asked for the wisdom of the Perl Monks concerning the following question:
I'm back again..
in prior topics I discussed a section of my code that allows my users to execute an arbitrary regular expression using
eval $w;
where $w contains the expression..
but, if they code it wrong, my application dies.
for example, expression= '/HOST=.*('
will yield a fatal die error..
Unmatched ( in regex; marked by <-- HERE in
but I don't want it to be fatal..
the contents of $w is (no quotes)
'$expdata =~ /HOST=.*(;'
but eval {$w;} is ignored
--- from the perl content on eval
eval '$x'; # CASE 3
eval { $x }; # CASE 4
Cases 3 and 4 likewise behave in the same way: they run the code '$x', which does nothing but return the value of $x.
---
and I can confirm that the expression itself does not execute.
So.. is there some trick to this?
thanks
Re: capture errors from eval
by ikegami (Patriarch) on Sep 24, 2012 at 01:13 UTC
|
use strict;
use warnings;
my $w = '$expdata =~ /HOST=.*(;';
eval $w;
eval catches fatals errors and places the message in $@.
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: capture errors from eval
by tobyink (Canon) on Sep 23, 2012 at 21:05 UTC
|
eval { eval $w }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
| [reply] [Watch: Dir/Any] [d/l] |
|
sorry, actually this does work!.. had two places and only tested on one (the wrong one obviously!)..
thank you
| [reply] [Watch: Dir/Any] |
|
sorry, dumb answer.. only tested in one of two places..
this works great and $@ contains the error text..
| [reply] [Watch: Dir/Any] |
Re: capture errors from eval
by BrowserUk (Patriarch) on Sep 23, 2012 at 21:28 UTC
|
C:\test>perl -E"eval{ $SIG{__DIE__}='ignore'; eval $ARGV[0]; } say 'go
+t here';" "$expdata =~ /HOST=.*(;"
got here
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP Neil Armstrong
| [reply] [Watch: Dir/Any] [d/l] |
Re: capture errors from eval
by tinita (Parson) on Sep 24, 2012 at 09:34 UTC
|
my $re = eval { qr/$x/ };
if ($@) { ... }
else { $string =~ $re }
| [reply] [Watch: Dir/Any] [d/l] |
|