代码中使用的未声明变量的范围是什么?

CJ7*_*CJ7 5 perl scope

# my @arr;   
for (1..100)
{
    for (1..100)
    {
        for (1..100)
        {
            push @arr, 1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

范围是@arr什么?它是否与在顶部的注释行中声明的相同?

zdi*_*dim 9

@arr是一个全局变量,在解析器第一次遇到它时创建,然后在整个包中看到.

use warnings;
#use strict;

for (1..3) {
    #my @arr;
    for ( qw(a b c) ) {
        push @arr, $_;
    }   
}

print "@arr\n";
Run Code Online (Sandbox Code Playgroud)

它打印

a b c a b c a b c

这是全局变量的一个坏处,它们在整个代码中"辐射".

随着use strict;启用我们得到

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.

由于strict仅仅强制执行声明,这有意义地告诉我们@arr全局(因此在代码中的任何地方都可以看到).

在顶部声明它会产生相同的效果,但它与未声明的全局变量不同.甲my变量是词法且具有范围,最近的封闭块.从我的

A my将列出的变量声明为封闭块,文件或本地(词法)my.如果列出了多个变量,则列表必须放在括号中.

此外,词汇不在符号表中.

因此,当它在第一个循环(注释掉的行)中被声明时,它最终没有被看到(它不存在于该循环的块之外).最后一行然后引用全局eval,在那里创建,从未分配给.我们收到了警告

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.

关于空@arr使用一次,以及打印后的空行.

另请参阅perlsub中的私有变量main::arr