in reply to Finding a random line
You want to read the Perl Cookbook, chapter 8 (File Contents), page 284-285.
For your convenience, I put the code that does what you want in here.
Solution: Use rand() and $. to decide which line to keep:
rand($.) < 1 && ($line = $_) while <>; # $line is the random line
This works because you have a 1/N chance for line N to be kept. For more explanations, get the book.
Extending this example to choosing a random word from an array of words is left as an exercise for the reader (I always wanted to say that!) ...
Christian Lemburg
Brainbench MVP for Perl
http://www.brainbench.com
|
|---|