hepcat72
hepcat72

Reputation: 1124

how to eval regular expression with embedded perl code

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

Upvotes: 4

Views: 1764

Answers (1)

ikegami
ikegami

Reputation: 386501

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

Upvotes: 5

Related Questions