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

Re: [MacPerl] Random lines from a File



Matthias Neeracher wrote:
> 
> 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.
> 

We had the same idea in how to solve this problem.  But...

> #!/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, $_;

This method strongly favors lines nearer the end of the file.  Each newly
selected line replaces the first line in the ordered array.

> 	  }
>     }
> }
> 


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