Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
No such thing as a small change
 
PerlMonks  

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

by scain (Curate)
on Nov 30, 2001 at 16:53 UTC ( [id://128676]=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?

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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://128676]
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.