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

前端之家收集整理的这篇文章主要介绍了perl – 代码中使用的未声明变量的范围是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
# 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,or eval. 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使用过一次,并且打印后空行.

另见Private variables via my() in perlsub

猜你在找的Perl相关文章