Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by rob_au (Abbot)
on Dec 01, 2001 at 16:19 UTC ( [id://128858]=note: print w/replies, xml ) Need Help??


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

From Programming Perl (1st Ed) written by Larry Wall and Randal Schwartz ...

perl -e 'srand;' \ -e 'rand($.) < 1 && ($it = $_) while <>;' \ -e 'print $it' FILE

This procedure selects a line at random from a file, using just one pass over the file and without knowing in advance the number of lines. It works by calculating the probability that the current line (indicated by the $. variable) would be selected if this line were the last line in the file. The first line is selected with a probability of 100%, but the second line has a 50% chance of replacing the first one, the third line a 33% chance of replacing one of the first two, and so on.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://128858]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-24 08:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found