【问题标题】:Perl: unexpected results determining if a key is in a hashPerl:确定键是否在散列中的意外结果
【发布时间】: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);

和(基于this question's answer

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


【解决方案1】:

在 Perl 中,散列中的键要么存在,要么不存在。要检查密钥是否存在,请使用exists

if (exists $hvac_codes{$hvacstring}) { ...

您还可以使用defined 测试与键对应的值的定义性。

if (defined $hvac_codes{$hvac_string}) { ...

如果key不存在,它仍然返回false;但它也为分配值为undef的键返回false:

undef $hvac_codes{key_with_undef_value};

注意Data::Dumper 导出Dumper,而不是dumper。 Perl 区分大小写。

【讨论】:

  • 修复了!一旦我让 Dumper 工作,我很快就看到只有一行以哈希 %hvac_codes 结尾。问题是我忘记将my %hvac_codes; 移到主while 循环之外,并且每次都重新初始化。我最终的测试看起来像这样if (( exists $hvac_codes{$hvacstring} ) and ( $hvac_codes{$hvacstring} eq 1 )) {
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 2022-01-24
  • 2021-08-15
  • 2013-01-30
  • 2011-08-25
相关资源
最近更新 更多