And here my version based on insertion sort, complete with random data generation and testing:
use strict; use warnings; sub nextrecord { return undef unless shift; # generate random records return { code => join( " ", (int rand 10), (int rand 10), (in +t rand 10), (int rand 10) ), score => rand }; } my $keep = 10; my $counter = 1000; # initialize with the first 10 records sorted my @largest = sort { $a->{score} <=> $b->{score} } map nextrecord( $co +unter-- ), 1..$keep; my @test = @largest; # for testing while( my $next = nextrecord( $counter-- ) ){ push @test, $next; # keep all for testing my $pos = 0; # insertion sort while(($pos < $keep) && ($largest[$pos]->{score} < $next->{sco +re}) ) { $largest[$pos-1] = $largest[$pos] if $pos; $pos++; } $largest[$pos-1] = $next if $pos; } print map { "$_->{code}\t$_->{score}\n" } @largest; # test print "\n"; print map { "$_->{code}\t$_->{score}\n" } ( sort { $a->{score} <=> $b- +>{score} } @test )[-10..-1];
In reply to Re: Limit the size of a hash
by hdb
in thread Limit the size of a hash
by Dr Manhattan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |