use Heap::Simple; use strict; use warnings; # NB: will throw an exception for a variety of reasons, including # if the source produces fewer lines than the 'min' specified. sub get_N_longest { my( $min, $infile ) = @_; open my $infh, '<', $infile or die; my $heap = Heap::Simple->new( elements => 'Any', order => '>' ); local $_; # be nice to the caller. while ( <$infh> ) { chomp; $heap->key_insert( length($_), $_ ); } my @r; push @r, $heap->extract_upto( length $heap->top ) # top throws if heap empty while @r < $min; @r } printf "%6d %s\n", length($_), $_ for get_N_longest(10,'words.txt');