use warnings; use strict; my $limit = 40_000_000; my $how_many = $limit/2; my $hits = 0; open (my $handle, 'rand_sorted.txt') or die "Unable to open rand_sorted.txt: $!"; # Using a C style loop to avoid a large temp list (Grandfather) for (my $i = 0; $i < $limit && $hits < $how_many; $i++) { my $record = <$handle>; if (rand(2) > 1 || ($limit-$i) <= $hits ) { $hits++; # Do what you must to the record print "$i: $record\n"; } } close ($handle);