#!/usr/bin/perl rand($.) < 1 && ($line = $_) while <>; print $line;
for picking up to N random lines from a file:
------------start code-------------- #!/usr/bin/perl
die "Usage: $0 <N>, where N is the number of lines to pick\n" if @ARGV < 1; $N = shift @ARGV;
@pick = ();
while (<>) {
if (@pick < $N) {
push @pick, $_;
($r1, $r2) = (rand(@pick), rand(@pick));
($pick[$r1], $pick[$r2]) = ($pick[$r2], $pick[$r1]);
} else {
rand($.) <= $N and $pick[rand(@pick)] = $_;
}
}print @pick; -------------end code---------------
Could anyone verify if the algorithm is correct?
Thanks in advance, -- dave
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>
