2011-02-23 34 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]"; 
}