in reply to grabbing random n rows from a file
The fact that your sets are grouped is a great benefit. We can work with a set at a time.
The fact that your sets are of varying length is a great hindrance. Work needs to be done to locate the end of each set.
I made the following assumptions:
My solution:
use strict; use warnings; use List::Util qw( shuffle ); my $j = 90; sub extract_id { my ($line) = @_; ... return ...; } my @m; my $id; my $last_id; for (;;) { my $line = <DATA>; $id = extract_id($line) if defined($line); if (@m) { if (!defined($line) || $id ne $last_id) { my $j = $j < @m ? $j : @m; print $m[$_] foreach (shuffle(0..$#m))[0..$j-1]; @m = (); } } last if !defined($line); push(@m, $line); $last_id = $id; }
Untested. (Update: Tested. Fixed. )
Memory can be saved by stored file positions in @m instead of the actual lines, but that's not needed based on your "Update 2".
Alternative:
print splice(@m, rand(@m), 1) while $j--;
|
|---|