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

前端之家收集整理的这篇文章主要介绍了正则表达式 – 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;
原文链接:https://www.f2er.com/regex/357144.html

猜你在找的正则表达式相关文章