【发布时间】:2020-09-03 13:35:21
【问题描述】:
在 Windows 10 x64 上使用 Perl v5.22.1。 我已经设置了
use strict;
use warnings;
这段代码(基于@Jeef 的accepted answer in this question)是解析文件的while 循环的一部分。它默默地退出:
my %hvac_codes; # create hash of unique HVAC codes
#Check the hash to see if we have seen this code before we write it out
if ( $hvac_codes{$hvacstring} eq 1) {
#Do nothing - skip the line
} else {
$hvac_codes{$hvacstring} = 1;
}
如果我这样改变它
my %hvac_codes; # create hash of unique HVAC codes
#Check the hash to see if we have seen this code before we write it out
if ( defined $hvac_codes{$hvacstring} ) {
#Do nothing - skip the line
} else {
$hvac_codes{$hvacstring} = 1;
print (" add unique code $hvacstring \n");
}
它不会静默退出(也很好奇为什么静默退出而不是未定义引用上的错误)但不能按预期工作。每个 $hvacstring 都会被添加到 %hvac_codes 哈希中,即使它们已被添加。 (由印刷品证明)
我想看看哈希是如何结束的,以确定是否每个代码都被视为未定义,因为测试是错误的,或者分配给哈希的分配不起作用。我尝试了两种方式的倾倒器:
print dumper(%hvac_codes);
print dumper(\%hvac_codes);
在这两种情况下,转储程序行都会失败并出现Global symbol "%hvac_codes" requires explicit package name 错误,即使存在my %hvac_codes;。现在我已经把它注释掉了。
【问题讨论】:
-
对于以后发现此问题的任何人,在哈希上使用 Dumper 的正确语法是:
print Dumper(%hvac_codes);在这种情况下,前导反斜杠形式不起作用。 -
对于以后发现此问题的任何其他人,在哈希上使用
Data::Dumper的正确语法是print Dumper(\%hvac_codes)。如果没有前导反斜杠,哈希键和值将被视为单独的标量。
标签: perl hash data-dumper