Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do I pick a random line from a file?

by vroom (Pope)
on Jan 09, 2000 at 10:38 UTC ( #1911=categorized answer: print w/replies, xml ) Need Help??

Q&A > files > How do I pick a random line from a file? - Answer contributed by vroom

This solution while not the most obvious is probably the best because it doesn't require you to store the entire file in memory. Instead it reads in each line and chooses whether or not that line will be stored as the random line. $. is a special variable that stores the current line number you are on starting with 1.

To show that this works we'll walk through an example reading line 1 to 3.
1. read line 1 2. rand(1)<1 #100% chance it's true if we had just one line 3. read line 2 4. rand(2)<1 #50% chance that line 2 replaces line 1 as the random +line. 5. read line 3 6. rand(3)<1 #1/3 chance that line 3 replaces the currently chosen +line
srand; open FILE, "<filename" or die "Could not open filename: $!\n"; rand($.)<1 and ($line=$_) while <FILE>; close FILE; print "Random line is $line\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2017-11-25 12:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (355 votes). Check out past polls.

    Notices?