我在回调中得到一个变量$品种,我正在检查我之前是否已经看过它,如果我没有,请通过执行以下操作将其存储在%hash中:
if (exists $hash{$breed}) {
#exists
} else {
#add it
$hash{$breed};
}
现在,由于我想在单独的哈希中跟踪这些独特的$品种,我制作了另一个哈希以保留新的哈希名称
%hashnames =(cats => 'cathash',
dogs => 'doghash');
my %cathash = ();
my %doghash = ();
由于我也从我的回调中获得$物种,我知道我可以进行查找以获得正确的哈希我应该通过这样做来添加$品种:
$hashnames {$species}
我认为以下内容会好起来,但事实并非如此:
if (exists ${$hashnames {$species}}{$breed}){
#exists
}else{
#add it
${$hashnames {$species}}{$breed};
}
实际上,有数百种物种和品种。这可能吗?也许我一切都错了?感谢。
答案 0 :(得分:0)
您可以执行hash of hashes:
我不确定您是如何获取数据的,但这是一个可能的示例:
my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'], ['cats', 'persian cat'], ['dogs', 'german shepherd']); #generating data
my (%cats, %dogs);
my %species = ('cats' => \%cats, 'dogs' => \%dogs);
for my $specie_breed(@lol) {
my ($s, $b) = @{$specie_breed};
$species{$s}->{$b}++;
}
print Dumper \%species;
结果:
$VAR1 = {
'cats' => {
'persian cat' => 2
},
'dogs' => {
'german shepherd' => 1,
'border collie' => 1
}
};
以下是使用跳过散列中的数组的示例:
my @lol = (['cats', 'persian cat'], ['dogs', 'border collie'],
['cats', 'persian cat'], ['dogs', 'german shepherd'],
['cats', 'Siamese']); #generating data
my (@cats, @dogs);
my %species = ('cats' => \@cats, 'dogs' => \@dogs);
for my $specie_breed(@lol) {
my ($s, $b) = @{$specie_breed};
if(! grep(/$b/, @{$species{$s}})) {
push @{$species{$s}}, $b;
}
}
print Dumper \%species;
结果:
$VAR1 = {
'dogs' => [
'border collie',
'german shepherd'
],
'cats' => [
'persian cat', #only adds it once
'Siamese'
]
};