微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 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.jb51.cc/regex/357144.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐