Perl Regex'e'(eval)修饰符,带有s/// [英] Perl Regex 'e' (eval) modifier with s///

查看:98
本文介绍了Perl Regex'e'(eval)修饰符,带有s///的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理解/e regex修饰符的这种简单用法时,我遇到了一些麻烦.

I'm having a little trouble comprehending this simple use of the /e regex modifier.

my $var = 'testing';
$_ = 'In this string we are $var the "e" modifier.';

s/(\$\w+)/$1/ee;

print;

返回:在此字符串中,我们正在测试"e"修饰符."

Returns: "In this string we are testing the "e" modifier."

我看不到为什么需要两个'e'修饰符.据我所知,$ 1应该从字符串中捕获'$ var',然后一个'e'修饰符就应该能够将变量替换为其值.但是,我一定会误会,因为仅使用一个'e'修饰符尝试上述代码并不能明显替换字符串中的任何内容.

I cannot see why two 'e' modifiers are required. As far as I can see, $1 should capture '$var' from the string and a single 'e' modifier should then be able to replace the variable with its value. I must be misunderstanding something however, since trying the above code with just one 'e' modifier does not visibly replace anything in the string.

请问一个简单的问题!

谢谢.

推荐答案

这不完全是一个简单"的问题,因此请不要打beat.

It’s not exactly a "simple" question, so don’t beat yourself up.

问题在于,对于单个/e,RHS被理解为是其eval结果将用于替换的代码.

The issue is that with a single /e, the RHS is understood to be code whose eval’d result is used for the replacement.

那是什么RHS? $1.如果评估了$1,则会发现其中包含字符串 $var.它不包含所述变量的内容,仅包含$,其后是v,然后是a,然后是r.

What is that RHS? It’s $1. If you evaluated $1, you find that contains the string $var. It does not contain the contents of said variable, just $ followed by a v followed by an a followed by an r.

因此,您必须对其进行两次评估,一次将$1转换为$var,然后再次将$var的先前结果转换为字符串"testing".为此,请在 s运算符上使用双ee修饰符.

Therefore you must evaluate it twice, once to turn $1 into $var, then again to turn the previous result of $var into the string "testing". You do that by having the double ee modifier on the s operator.

通过运行一个/e而不是运行两个/e,可以很容易地检查它.这是两者的演示,还有使用符号解引用的第三种方法-由于它引用了包符号表,因此仅适用于包变量.

You can check this pretty easily by running it with one /e versus with two of them. Here’s a demo a both, plus a third way that uses symbolic dereferencing — which, because it references the package symbol table, works on package variables only.

use v5.10;

our $str = q(In this string we are $var the "e" modifier.);
our $var = q(testing);

V1: {
    local $_ = $str; 
    s/(\$\w+)/$1/e;
    say "version 1: ", $_;

}

V2: {
    local $_ = $str;
    s/(\$\w+)/$1/ee;
    say "version 2: ", $_;
}

V3: {
    no strict "refs";
    local $_ = $str;
    s/\$(\w+)/$$1/e;
    say "version 3: ", $_;
}

运行时会产生:

version 1: In this string we are $var the "e" modifier.
version 2: In this string we are testing the "e" modifier.
version 3: In this string we are testing the "e" modifier.

这篇关于Perl Regex'e'(eval)修饰符,带有s///的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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