检查哈希是否为空键,Perl

时间:2013-12-30 14:09:09

标签: perl hash

我有一个看起来像这样的哈希

$VAR1 = {
      '' => 0,
      'example' => 17953878,
      'test' => 14504908,
      'arbitrary' => 14977444
};

我用基本的

打印哈希
for (keys %hash) {
    print "$_ : $hash{$_}";
}

在打印哈希值之前检查空键并删除它的最佳方法是什么? 还想知道如何检查密钥是'undef'还是只是一个空字符串,它是否评估为false?等

2 个答案:

答案 0 :(得分:5)

for (keys %hash) {
    length  or next;     # key is empty string, skip it
    # $_ eq "" and next; # explicit comparison to ""

    print "$_ : $hash{$_}";
}

在循环外检查exists

print "hash has empty string key\n" if exists($hash{""});

答案 1 :(得分:2)

如果您的数据来自外部来源,并且您知道空字符串永远不是有效输入,那么您可以这样做

delete $hash{''};
打印前

相关问题