use strict; use warnings; sub nextrecord { return undef unless shift; # generate random records return { code => join( " ", (int rand 10), (int rand 10), (int 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( $counter-- ), 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->{score}) ) { $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];