问题
So I tested out a regular expression that utilizes the experimental embedded code features. My tests worked, so I expounded upon it to do a more sophisticated script, but ran into errors. I traced the errors to a simple use of a variable in the regular expression not in the embedded code. I tried doing the regex in the suggested eval, but discovered that that wouldn't work because I could not access special variables after the eval'ed regular expression. I eventually re-wrote the code to not use the embedded code strategy, but am left curious as to why it wouldn't work. I simplified the problem in a pair of perl one-liners below:
This works:
perl -e '$_ = "The brown fox jumps over the lazy dog ABC god yzal eht revo spmuj xof nworb ehT";
while (/(.{10,41})(?{$cap = $^N;$rev = r($cap);})(...)(??{$rev})/ig {
print("$1\n")
}
sub r { return(join("",reverse(split("",$_[0])))) }'
So why doesn't this?:
perl -e '$_ = "The brown fox jumps over the lazy dog ABC god yzal eht revo spmuj xof nworb ehT";
$f=10;
$e=41;
while (/(.{$f,$e})(?{$cap = $^N;$rev = r($cap);})(...)(??{$rev})/ig) {
print("$1\n")
}
sub r { return(join("",reverse(split("",$_[0])))) }'
The error I get is:
Eval-group not allowed at runtime, use re 'eval' in regex
m/(.{10,41})(?{$cap = $^N;$rev = r($cap);})(...)(??{$rev})/ at -e line 1.
Is there a way to make it work with the $f
and $e
variables - a way that allows me to use the special variables
$`, $&, $', and @-
afterwards? Do I need to use eval?
Thanks, Rob
回答1:
You need to use
use re 'eval';
It lets Perl know you are aware that the pattern being interpolated can evaluate arbitrary code and that you're ok with that. It's lexically-scoped, so it will only affect the regular expressions in the file or in the curlies where it is used.
Since you have a one-liner, you can do the same using the command line option
-Mre=eval
来源:https://stackoverflow.com/questions/16320545/how-to-eval-regular-expression-with-embedded-perl-code