鉴于以下代码
#!/usr/bin/perl
use Data::Dumper;
my %hash;
my @colos = qw(ac4 ch1 ir2 ird kr3);
foreach my $colo (@colos) {
if(exists $hash{output}{$colo}) {
print "$colo is in the hash\n";
}
}
print Dumper(\%hash);
我有一个创建的空哈希。我有一个包含一些缩写的数组。如果我循环遍历数组以查看这些人是否在散列中,则不会向 STDOUT 显示任何预期的内容,但由于某种原因创建了 $hash{output}。这根本不符合逻辑。我所做的只是 if 存在。我哪里做错了?
最佳答案
exists
在给定的散列中查找散列元素。您的代码正在自动生成哈希
%{ $hash{output} }
并检查是否带有键 $colo
的哈希元素存在于该哈希中。
请尝试以下操作:
if(exists $hash{output}{$colo}) {
变成
if(exists $hash{output} and exists $hash{output}{$colo}) {
当然,您可以编写一个从代码中隐藏这种复杂性的子程序。
关于perl - 检查散列键是否存在创建键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9789333/