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

前端之家收集整理的这篇文章主要介绍了正则表达式 – Perl:为什么不eval’/(…)/’设置$1?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果在eval内部发生正则表达式匹配,则与外部环境不可见的捕获相关变量($1等)的更改.这是一个bug吗?

perlop和perlre似乎没有提到任何这样的限制.

例如:

  1. use strict; use warnings;
  2. $_ = "hello";
  3. eval '/(.*)/';
  4. print "GOT: $1\n";

得到:

  1. Use of uninitialized value $1 in concatenation (.) or string at -e line 1.
  2. GOT:

更简洁的演示是:

  1. 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 […]

@H_403_24@

请注意,这一点的文档是absent from the 5.12.4 perldoc.

问题是局部变量.我的perldoc -f eval (5.12.4)副本有这样的说法:

  1. The assignment to $@ occurs before restoration of localised
  2. variables,which means a temporary is required if you want to
  3. mask some but not all errors: [...]

联机帮助页并没有对所有这些特殊的全局变量(如$1,$和amp;可能还有其他变量)做出明确的声明,但阻止本地化和后续恢复是在这里发生的.

将变量分配给eval内部,一旦eval块保留,原始值就会被恢复.

  1. use strict; use warnings;
  2. use Test::More;
  3. use constant V => 'hello';
  4.  
  5. $_ = V;
  6.  
  7. note '*** block eval';
  8. eval {
  9. is $_,V,'input ok';
  10. /(.*)/;
  11. is $&,'in eval'; is $1,'in eval';
  12. };
  13. is $&,'after eval'; is $1,'after eval';
  14.  
  15. note '*** without eval';
  16. is $_,'input ok';
  17. /(.*)/;
  18. is $&,V; is $1,V;
  19.  
  20. done_testing;

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