Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Limit the size of a hash

by space_monk (Chaplain)
on Sep 05, 2013 at 08:42 UTC ( #1052516=note: print w/replies, xml ) Need Help??

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! :-)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052516]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2018-03-24 13:04 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (298 votes). Check out past polls.