正则表达式 – Perl:为什么不eval’/(…)/’设置$1?
发布时间:2020-12-14 06:29:16 所属栏目:百科 来源:网络整理
导读:如果在eval内部发生正则表达式匹配,则与外部环境不可见的捕获相关变量($1等)的更改.这是一个bug吗? perlop和perlre似乎没有提到任何这样的限制. 例如: use strict; use warnings; $_ = "hello"; eval '/(.*)/'; print "GOT: $1n"; 得到: Use of uninitia
如果在eval内部发生正则表达式匹配,则与外部环境不可见的捕获相关变量($1等)的更改.这是一个bug吗?
perlop和perlre似乎没有提到任何这样的限制. 例如: use strict; use warnings; $_ = "hello"; eval '/(.*)/'; print "GOT: $1n"; 得到: Use of uninitialized value $1 in concatenation (.) or string at -e line 1. GOT: 更简洁的演示是: perl -we '$_="foo"; eval q(/(.*)/;) ; print "GOT:$1n";'
文档证明,本地化变量在这里是
perlvar of 5.14.0:
请注意,这一点的文档是absent from the 5.12.4 perldoc. 问题是局部变量.我的 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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容