http://www.perlmonks.org?node_id=1052516


in reply to Limit the size of a hash

You could use a package such as Tie::Array::Sorted to maintain a sorted array of your 10 highest scores (mapped to the corresponding code); once the array increases in size to above 10, just remove the lowest (last) item on the array as you go through the file.
The following needs a little refinement/ debugging, but shows an outline of how I think it should work....
use Tie::Array::Sorted; tie @a, "Tie::Array::Sorted", sub { $_[0]->{score} <=> $_[1]->{score} +}; # read file line by line while (<FH>) { # use split if you hate regexs... :-) if ( /((\d ){4})(\d.\d+)/) { # add new element to array push @a, { 'score' => $2, 'code' => $1 }; # remove lowest scoring element if more than 10 if ($#a > 10) { pop @a; # remove lowest scoring/last element } } }
If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)