Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2019-10-18 01:33 GMT
Find Nodes?
    Voting Booth?