my %HASH; foreach('AA' .. 'ZZ') { $HASH{$_} = 1 + int rand 1000; } my $keep = 20; my @top; if(scalar keys %HASH <= $keep) { # You actually need to show them all. @top = sort { $b->[1] <=> $a->[1] } map [$_, $HASH{$_}], keys %HASH; } else { my $threshold; while(my($key, $value) = each %HASH) { if(@top < $keep) { printf "Adding %s => %d\n", $key => $value; push @top, [$key, $value]; $threshold = $value if !defined $threshold or $value > $threshold; } elsif($value > $threshold) { @top = sort { $b->[1] <=> $a->[1] } @top, [$key, $value]; printf "Inserting %s => %d\n", $key => $value; $threshold = $top[$keep-1][1]; printf "New threshold: %d\n", $threshold; while($top[-1][1] < $threshold) { printf "Popping %s => %d\n", @{$top[-1]}; pop @top; } printf "Keeping %d items\n", scalar @top; } elsif($value == $threshold) { printf "Adding %s => %d\n", $key => $value; push @top, [$key, $value]; } } } use Data::Dumper; $Data::Dumper::Terse = 1; print Dumper \@top;