my $N = 20; my $collect = 5 * $N; while (<>) { my ($id, $score) = split ' '; push @top, [$id, $score]; if(@top > $collect) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; } } if(@top > $N) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; }