perl - 为什么某些全局符号需要显式的包名称

标签 perl

为什么下面的代码中第 18 行需要显式的包名称?

#! /usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw<say state>;

{
    no strict;
    no warnings;

    $myRef{G4143} = 58;
    $myRef{Emily} = 8;
    $myRef{Angela} = 40;

}

#%myRef requires explicit package name
while (my ($key, $value) = each %myRef) {
    say "$key=>$value";
}

exit(0);

如果我在第 18 行将主包添加到 %myRef,那么它就可以工作

#! /usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw<say state>;

{
    no strict;
    no warnings;

    $myRef{G4143} = 58;
    $myRef{Emily} = 8;
    $myRef{Angela} = 40;

}
#added package name and now it works
while (my ($key, $value) = each %main::myRef) {
    say "$key=>$value";
}

exit(0);

为什么此示例中需要包名称?

最佳答案

您需要显式指定包名称,因为

  1. strict已启用
  2. %myRef尚未在该范围或任何封闭范围内声明(使用 myouruse vars )

不需要前面的 block 中的包名称,因为 strict在该 block 内关闭。

如果添加行 my %myRef; (或者 our %myRef; 如果您希望它在当前文件和包之外可见)在 no strict 之前 block ,那么您将不再需要显式的包名称,也不需要 no strict在 block 内。

还有no warnings已经是多余的了,所以我建议删除它。在任何情况下,该 block 中都不会生成警告。

关于perl - 为什么某些全局符号需要显式的包名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447494/

相关文章:

string - Perl:在 "display"上打印并打印到文件中

javascript - 确定 rar 文件是否受密码保护

perl - 禁用不适当的缓冲 Perl

perl - 如何同时为两个 perl 安装安装模块?

linux - Perl - 在 Linux 上获取可用磁盘空间使用情况

arrays - 在 perl 中使用 <$socket[i]> 读取数组中的套接字

perl - 编辑 Google Storage 对象元数据需要哪些权限?

perl - 在安装 conda 包期间更新 @INC 变量

regex - 您在正则表达式中使用过 Perl 5.10 回溯控制动词吗?

perl - 如何在 perl 中将数字转换为任意基数?