gpt4 book ai didi

regex - Perl:为什么 eval '/(...)/' 不设置 $1?

转载 作者:行者123 更新时间:2023-12-03 23:43:09 24 4
gpt4 key购买 nike

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

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

最佳答案

文件证明local化变量是这里的问题在 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 .

问题是 local化变量。我的副本 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$& ,可能还有其他)做出明确的声明,但是块本地化和随后的恢复似乎是在这里发生的。
变量被分配到 eval 内部并且一旦 eval恢复原始值块被留下。
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;

关于regex - Perl:为什么 eval '/(...)/' 不设置 $1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10909127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com