- 论坛徽章:
- 46
|
回复 7# bighead1982
没调用 test_static 直接调用 next_counter 的话它需要访问一个根本还不存在的词法变量,这个怎么都讲不通的,只能说目前的实现是我说的这样。目前有这么个警告 5.024
Variable "%s" will not stay shared(W closure) An inner (nested) named subroutine is referencing alexical variable defined in an outer named subroutine.
When the inner subroutine is called, it will see the value ofthe 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 theouter subroutine is complete, the inner and outer subroutines will nolonger share a common value for the variable. In other words, thevariable will no longer be shared.
This problem can usually be solved by making the inner subroutineanonymous, using the [url=]sub[/url] {} syntax. When inner anonymous subs thatreference variables in outer subroutines are created, theyare automatically rebound to the current values of such variables.
test_static 每次调用都会生成一个 $counter ,但 next_counter 只跟第一次调用共享这个 $counter 变量,test_static 没调用时会先记着,第一次调用 test_static 时会补上,第二次 test_static 就变成个普通的函数了。
sub test_static
{
my $counter;
sub next_counter {
$counter+=2;
return $counter;
}
say $counter; # 第一次调用时会记得 next_counter 对 $counter 的修改
$counter = 5;
print "counter= $counter\n";
}
say next_counter;
say next_counter;
test_static;
say next_counter;
|
|