如何使用嵌入式Perl代码评估正则表达式 [英] how to eval regular expression with embedded perl code

查看:64
本文介绍了如何使用嵌入式Perl代码评估正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我测试了一个利用实验性嵌入式代码功能的正则表达式.我的测试有效,因此我对它进行了阐述,以编写更复杂的脚本,但遇到了错误.我跟踪错误的原因是在正则表达式中而不是在嵌入式代码中简单地使用了变量.我尝试在建议的eval中进行正则表达式,但是发现那是行不通的,因为在eval的正则表达式之后我无法访问特殊变量.我最终重新编写了代码,使其不使用嵌入式代码策略,但对为什么它不起作用感到好奇.我在下面的一对perl单行代码中简化了这个问题:

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:

这有效:

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])))) }'

那为什么不呢?

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])))) }'

我得到的错误是:

Eval-group not allowed at runtime, use re 'eval' in regex 
m/(.{10,41})(?{$cap = $^N;$rev = r($cap);})(...)(??{$rev})/ at -e line 1.

有没有办法使它与$f$e变量一起使用-一种使我可以使用特殊变量的方法

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 @- 

之后呢?我需要使用eval吗?

afterwards? Do I need to use eval?

谢谢, 罗布

推荐答案

您需要使用

use re 'eval';

它使Perl知道您知道插值的模式可以评估任意代码,并且您可以接受.它具有词法作用域,因此只会影响文件或使用它的curl中的正则表达式.

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

这篇关于如何使用嵌入式Perl代码评估正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆