Variable "$np" will not stay shared at (re_eval 8) line 2 (#1)
(W closure) An inner (nested) named subroutine is referencing a
lexical variable defined in an outer named subroutine.When the inner subroutine is called,it will see the value of
the outer subroutine’s variable as it was before and during the first
call to the outer subroutine; in this case,after the first call to the
outer subroutine is complete,the inner and outer subroutines will no
longer share a common value for the variable. In other words,the
variable will no longer be shared.This problem can usually be solved by making the inner subroutine
anonymous,using the sub {} Syntax. When inner anonymous subs that
reference variables in outer subroutines are created,they
are automatically rebound to the current values of such variables.
我已经完成了对Google的尽职调查:link,但仍然不明白如何在我的案例中应用这一点.
我还回到了代码片段的source,导致了这个问题.该片段再次在下方生成,以便于参考:
# parentheses balance pattern # @ http://www.unix.org.ua/orelly/perl/prog3/ch05_10.htm $np= qr{ \( ( (?: (?> [^()]+ ) # Non-parens without backtracking | (??{ $np }) # Group with matching parens )* ) \) }x;
我认为在同一个变量$np的定义中嵌套的$np会导致此警告.
请帮忙.谢谢!
解决方法
sub f { my $np; $np = qr/...(??{ $np }).../; }
(?? {…})在编译模式时捕获其中的词法.
在您的情况下,因为模式是常量,所以qr //中的正则表达式模式是在编译qr //本身时编译的.不幸的是,每次运行该函数时都会创建一个新的$np.
您可以通过避免词法变量来解决问题.
sub f { local our $np; $np = qr/...(??{ $np }).../; ... /$np/ ... }
或者通过强制通过使模式变量执行qr //来编译正则表达式模式.
sub f { my $var = ''; my $np; $np = qr/...(??{ $np })...$var/; ... /$np/ ... }
但为什么要重复执行qr //以获得恒定模式?最好的解决方案是将模式移出子模块.
my $np; $np = qr/...(??{ $np }).../; sub f { ... /$np/ ... }