in reply to Size-limited, fitness-based lists
This is when a little schooling comes in handy. ;-)
What you want is a Heap.
One nice module for heaps is Heap::Simple. Et voilą:
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');
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Size-limited, fitness-based lists
by AppleFritter (Vicar) on Aug 09, 2015 at 09:39 UTC | |
by Athanasius (Archbishop) on Aug 09, 2015 at 12:42 UTC | |
by tye (Sage) on Aug 09, 2015 at 17:41 UTC | |
by GotToBTru (Prior) on Aug 10, 2015 at 14:33 UTC | |
by tye (Sage) on Aug 10, 2015 at 16:08 UTC | |
by Corion (Patriarch) on Aug 10, 2015 at 14:39 UTC | |
by GotToBTru (Prior) on Aug 10, 2015 at 14:59 UTC | |
by jdporter (Paladin) on Aug 10, 2015 at 20:33 UTC | |
by tye (Sage) on Aug 10, 2015 at 21:41 UTC |