正则表达式 – Perl:为什么不eval’/(…)/’设置$1?

如果在eval内部发生正则表达式匹配,则与外部环境不可见的捕获相关变量($1等)的更改.这是一个bug吗?

perlop和perlre似乎没有提到任何这样的限制.

例如:

use strict; use warnings;
 $_ = "hello";
 eval '/(.*)/';
 print "GOT: $1\n";

得到:

Use of uninitialized value $1 in concatenation (.) or string at -e line 1.
GOT:

更简洁的演示是:

perl -we '$_="foo"; eval q(/(.*)/;) ; print "GOT:$1\n";'
文档证明,本地化变量在这里perlvar of 5.14.0

These variables are read-only and dynamically-scoped,unless we note otherwise.

The dynamic nature of the regular expression variables means that their value is limited to the block that they are in […]

请注意,这一点的文档是absent from the 5.12.4 perldoc.

问题是局部变量.我的perldoc -f eval (5.12.4)副本有这样的说法:

The assignment to $@ occurs before restoration of localised
variables,which means a temporary is required if you want to
mask some but not all errors: [...]

联机帮助页并没有对所有这些特殊的全局变量(如$1,$和amp;可能还有其他变量)做出明确的声明,但阻止本地化和后续恢复是在这里发生的.

将变量分配给eval内部,一旦eval块保留,原始值就会被恢复.

use strict; use warnings;
use Test::More;
use constant V => 'hello';

$_ = V;

note '*** block eval';
eval {
        is $_,V,'input ok';
        /(.*)/;
        is $&,'in eval'; is $1,'in eval';
};
is $&,'after eval'; is $1,'after eval';

note '*** without eval';
is $_,'input ok';
/(.*)/;
is $&,V; is $1,V;

done_testing;

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...