下面是Perl中的哈希:
my %hash = (
'episode1' => {
'when' => '08.13.97',
'airdate' => '08.13.97',
'episodenumber' => '101',
'id' => '103511',
'title' => 'Cartman Gets an Anal Probe',
'available' => 'true'
},
'episode2' => {
'when' => '08.20.97',
'airdate' => '08.20.97',
'episodenumber' => '102',
'id' => '1035156',
'title' => 'Weight Gain 4000',
'available' => 'true'
}
);
我想打印" id"两集都有,但下面的代码不起作用:
foreach my $key1 ( keys %hash ) {
foreach my $key2 ( keys %{$hash{$key1}} ) {
print "$hash{$key1}{$key2}{id}\n";
}
}
请帮忙。
答案 0 :(得分:4)
问题在于您正在尝试打印不存在的内容:没有与$hash{$key1}{$key2}{id}
匹配的值。
尝试使用此代码,该代码打印出具有键“id”的哈希哈希值:
use strict;
use warnings;
for my $episode (keys %hash){
print "$hash{$episode}{id}\n";
}
103511
1035156
答案 1 :(得分:1)
尝试使用map
:
my @ids = map { $hash{$_}{"id"} } sort keys %hash;
或者如果您仍然需要将结果作为哈希:
my %ids_by_key = map { ($_, $hash{$_}{"id"}) } keys %hash;
答案 2 :(得分:-1)
试试这个:
foreach my $key1 ( keys %hash ) {
print "$hash{$key1}{id}\n";
}
或
foreach my $key1 ( keys %hash ) {
foreach my $key2 ( keys %{$hash{$key1}} ) {
print "$hash{$key1}{$key2}\n" if($key2 eq 'id');
}
}