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

Answers


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

Need Your Help

Change variable with different attribute

css less

On our Website we have a section with multiple sites who all uses different color codes. I would like to keep it simple and change the color on a specific value inside a data-attribute, like this:

ToolBar not visible in 9930 simulator

blackberry toolbar

I've added a bottom toolbar using a ToolbarManager which shows in the 9800 and 9520(which have a similar screen size) simulator but not in the 9930 simulator. I haven't tested this on an actual 993...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.