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

Re: [MacPerl] Random lines from a File



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.  :)


>   #!perl -wl
>   my($file, $lines) = 'Shuck Manual';
>   open F, $file or die $!;
> 
>   for (1..5) {
>     print get_random_line();
>   }
> 
>   sub get_random_line {
>     local $.;
>     my $line;
>     seek(F, 0, 0);
>     rand($.) < 1 && (chomp($line = $_)) while <F>;
>     return $line;
>   }
>   __END__
> 

This one could select the same line more than once as well.  Is that a bug
or a feature?


> It is an adaptation of the entry in the FAQ and Cookbook.  I don't fully
> understand it, so don't ask me.  :)
> 


I can post a proof of why this solution works, if there's interest.

Ronald

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