Perl 正则表达式 'e' (eval) 修饰符,带 s/// [英] Perl Regex 'e' (eval) modifier with s///
问题描述
我在理解/e 正则表达式修饰符的这种简单用法时有点困难.
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.
不好意思问这么简单的问题!
Excuse me for asking such a simple question!
谢谢.
推荐答案
这不是一个简单"的问题,所以不要自责.
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"
.您可以通过在 ee 修饰符来做到这一点>s
运算符.
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
与其中两个来运行它来轻松检查这一点.这是一个演示 a both,以及使用符号解引用的第三种方法 - 因为它引用包符号表,所以仅适用于包变量.
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 正则表达式 'e' (eval) 修饰符,带 s///的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!