# my @arr; for (1..100) { for (1..100) { for (1..100) { push @arr,1; } } }
@arr的范围是什么?它是否与在顶部的注释行中声明的相同?
解决方法
@arr是一个全局变量,在解析器第一次遇到它时创建,然后在整个包中看到.
use warnings; #use strict; for (1..3) { #my @arr; for (1..3) { push @arr,$_; } } print "@arr\n";
它打印
1 2 3 1 2 3 1 2 3
用严格;我们得到了
Possible unintended interpolation of @arr in string at scope.pl line 11. Global symbol "@arr" requires explicit package name at scope.pl line 7. Global symbol "@arr" requires explicit package name at scope.pl line 11. Execution of scope.pl aborted due to compilation errors.
由于严格只是强制声明,这有意义地告诉我们@arr是全局的(因此在代码中的任何地方都可以看到).
在顶部声明它会产生相同的效果,但它与未声明的全局变量不同.我的变量是词法并且具有范围,最近的封闭块.从my起
A
my
declares the listed variables to be local (lexically) to the enclosing block,file,oreval
. If more than one variable is listed,the list must be placed in parentheses.
此外,词汇不在符号表中.
因此,当它在第一个循环(注释掉的行)中被声明时,它最终没有被看到(它不存在于该循环的块之外).最后一行然后引用在那里创建的全局@arr,它从未被分配给.我们收到了警告
Possible unintended interpolation of @arr in string at scope.pl line 11. Name "main::arr" used only once: possible typo at scope.pl line 11.
关于空的main :: arr使用过一次,并且打印后空行.