Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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

by scain (Curate)
on Nov 30, 2001 at 21:53 UTC ( #128676=categorized answer: print w/replies, xml ) Need Help??

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

I realize this is not at all portable, but one could use the wc -l *nix command to get the total number of lines, pick from that number randomly, then open the file and while until you get to that line. You could even use File::ReadBackwards if the random line is in the second half of the file.

Come to think of it, if you are already willing to use wc, you could also use tail and head thusly: $line = `tail +N | head -1 $file. Ugly, I know. It also opens all kinds of ugly security holes if $file comes from an untrustworthy source.

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 examining the Monastery: (8)
As of 2019-10-14 20:59 GMT
Find Nodes?
    Voting Booth?