2011-02-23 33 views
2
my $app = "info"; 
my %records; 
for($i = 0; $i<5; $i++) 
{ 
[email protected]{$records{$app}{"id"}},$i; 
[email protected]{$records{$app}{"score"}}, $i+4; 
} 

所以有5個ids [0,1,2,3,4,5]和5個分數。我的問題是如何迭代每個id和相應的分數。 。請幫我..basically我想打印結果這樣如何遍歷perl中的多級哈希

id score 
0 4 
1 5 
2 6 
3 7 
4 8 
5 9 

回答

0
printf "id\tscore\n"; 
for my $app (keys %records) { 
    my $apprecordref = $records{$app}; 
    my %apprecord = %$apprecordref; 

    my $idlen = scalar(@{$apprecord{"id"}}); 
    for ($i = 0; $i < $idlen; $i++) { 
     printf "%d\t%d\n", $apprecord{"id"}[$i], $apprecord{"score"}[$i]; 
    } 
} 

id score 
0 4 
1 5 
2 6 
3 7 
4 8 

或者是在這裏做一個不同的方式,我認爲是更容易一點:

my $app = "info"; 
my %records; 
for (my $i = 0; $i < 5; $i++) 
{ 
    # $records{$app} is a list of hashes, e.g. 
    # $records{info}[0]{id} 
    push @{$records{$app}}, {id=>$i, score=>$i+4}; 
} 

printf "id\tscore\n"; 
for my $app (keys %records) { 
    my @apprecords = @{$records{$app}}; 

    for my $apprecordref (@apprecords) { 
     my %apprecord = %$apprecordref; 
     printf "%d\t%d\n", $apprecord{"id"}, $apprecord{"score"}; 
    } 
} 
1

試試這個:

print "id\tscore"; 
for($i=0; $i<5; $i++) { 
    print "\n$records{$app}{id}[$i]\t$records{$app}{score}[$i]"; 
}