Perl:为什么不评估'/(...)/'设置$ 1? [英] Perl: Why doesn't eval '/(...)/' set $1?

查看:132
本文介绍了Perl:为什么不评估'/(...)/'设置$ 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If a regular expression match occurs inside an eval, changes to the capture-related variables ($1, etc.) are not visible in the outside environment. Is this a bug?

perlop perlre 似乎没有提及任何此类限制.

perlop and perlre don't seem to mention any such restriction.

例如:

 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";'

推荐答案

Documentation proof that localized variables are the issue here is in 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 [...]

请注意,这部分文档是 5.12.4 perldoc中缺少的

Note that this bit of documentation is absent from the 5.12.4 perldoc.

问题是local个变量.我的 perldoc -f eval(5.12.4)的副本是这样说的:

The problem is localized variables. My copy of perldoc -f eval (5.12.4) has this to say:

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$&以及其他可能的变量)做出明确声明,但此处似乎发生了块定位和后续恢复.

The manpage doesn't make an explicit statement for all such special global variables (like $1, $&, and probably others), but block localization and subsequent restoration is what appears to happen here.

将变量分配到eval内部,并在保留eval块后恢复原始值.

The variables are assigned to inside the eval and the original values are restored once the eval block is left.

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

$_ = V;

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

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

done_testing;

这篇关于Perl:为什么不评估'/(...)/'设置$ 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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