in reply to Re: Re: Re: Sorting values of nested hash refs
in thread Sorting values of nested hash refs

doran,
I think you might find the following a bit more efficient and a bit more readable:
# An inline loop is more efficient then a block - thought almost imper +ceptable $KP->{ $_->{k} }{ $_->{v} }++ while $kills_sth->fetchrow_hashref(); # Before I did not know if it was safe to assume no negative numbers - + now I can my %top = map { $_ => {'score' => 0, 'pid' => '', 'tid' => ''} } 1 .. +10; my @items = qw(score pid tid); for my $pid ( keys %{ $KP } ) { SCORE: for my $tid ( keys %{ $KP->{$pid} } ) { my $score = $KP->{$pid}{$tid}; next if $score < $top{10}{score}; # May or may not improve +efficiency for my $rank ( 1 .. 10 ) { if ( $score > $top{$rank}{score} ) { (@{$top{$rank}}{@items}, @{$top{$rank + 1}}{@items}) = + ($score, $pid, $tid, @{$top{$rank}}{@items}); next SCORE; } } } } for my $rank ( 1 .. 10 ) { printf("%.2d. f: %s\tp: %s\tt: %s\n", $rank, @top{@items}); }
This would be much more efficient if it could be done with SQL. You would have to provide more info to determine that.

Cheers - L~R

Update: 2004-03-17 This is broken. To fix it you would make %top an AoA, handle fence post issues, and splice entries in the middle while popping off the end. This version will randomly lose values. See this for a working example.