Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^3: Limit the size of a hash

by hdb (Monsignor)
on Sep 05, 2013 at 14:16 UTC ( [id://1052578]=note: print w/replies, xml ) Need Help??


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

I am usually careful with default values. Here you implicitely assume that all scores are positive, otherwise the zeroes could influence the result...

Replies are listed 'Best First'.
Re^4: Limit the size of a hash
by Random_Walk (Prior) on Sep 06, 2013 at 10:21 UTC

    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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1052578]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-24 09:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found