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

Re^4: Limit the size of a hash

by Random_Walk (Prior)
on Sep 06, 2013 at 10:21 UTC ( #1052689=note: print w/replies, xml ) Need Help??


in reply to Re^3: Limit the size of a hash
in thread Limit the size of a hash

Good point. Here is a better version that does not have to define this list first and does not make any assumptions about the size values.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $keep = 5; my @keeper; while (<DATA>) { my @vals = split; next unless @vals; # possibly more sophisticated test my $score = pop @vals; addlist ([$score, \@vals], \@keeper); } print Dumper \@keeper; # slide up the list knocking down existing records # until we no longer have the biggest sub addlist { my ($rec, $list) = @_; for my $i (0 .. $keep-1) { if (not $list->[$i] or $rec->[0] > $list->[$i]->[0]) { $list->[$i-1] = $list->[$i] if $i; $list->[$i] = $rec; } else { last; } } } __DATA__ 0 5 3 7 0.97 1 3 4 8 0.18 1 4 4 8 0.21 1 7 4 4 0.22 1 8 4 8 0.52 1 9 4 1 0.16 1 5 1 8 0.18 1 5 2 9 0.72 1 5 5 8 0.32 1 5 6 6 0.17 1 5 7 4 0.52 1 5 9 3 0.92 1 5 4 8 0.99 6 8 4 6 0.54

Cheers,
R.

Pereant, qui ante nos nostra dixerunt!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052689]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2021-01-27 01:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?