[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Random lines from a File



In article <199903042113.QAA21270@linguist.dartmouth.edu>, rjk@linguist.dartmouth.edu (Ronald J. Kimball) writes:
> Chris Nandor wrote:
>> 
>> Well, here is a slight improvement.  Improvement in that it does not read
>> the whole file into memory at once.
>> 

> But a disimprovement in that it has to read the whole file five times over!

> I don't think either inefficiency is desirable.  :)

Right.

Here's my entry. Note that the relative order of the selected lines is
preserved in this algorithm, which might not be what you want.

#!/usr/local/bin/perl

$lines = shift @ARGV;

@lines = ("") x $lines;

get_random_lines(\@lines);

print @lines;

sub get_random_lines {
    my($lines) = @_;
    while (<>) {
	  if (rand($.) < scalar(@$lines)) {
	     shift @$lines;
	     push @$lines, $_;
	  }
    }
}

Matthias

-- 
Matthias Neeracher   <neeri@iis.ee.ethz.ch>   http://www.iis.ee.ethz.ch/~neeri
  "And that's why I am going to turn this world upside down, and make
   of it a fire so *bright* that someone real will notice"
                                -- Vernor Vinge, _Tatja Grimm's World_

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org