Beefy Boxes and Bandwidth Generously Provided by pair Networks RobOMonk
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by vroom (His Eminence)
on Jan 09, 2000 at 05:38 UTC ( [id://1911]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to How do I pick a random line from a file?

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1911]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.