Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

How do I select a random line from a file?

by faq_monk (Initiate)
on Oct 13, 1999 at 03:42 UTC ( [id://820] : perlfaq nodetype . print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

Here's an algorithm from the Camel Book:

    srand;
    rand($.) < 1 && ($line = $_) while <>;

This has a significant advantage in space over reading the whole file in. A simple proof by induction is available upon request if you doubt its correctness.