[users] Re: random lines
"Martin F. Krafft" <madduck@madduck.net> wrote:
> also sprach Thomas J. Hamman (on Sun, 01 Jul 2001 11:58:32AM -0400):
> > What exactly is this for? You could use fortune and strfile. Make
> > the text file with a % symbol between each selection, like this:
>
> a list of albums that i have on mp3 format. and
> the desire to have a script that plays albums randomly
> -- not a random song off any album,
> but a random album from beginning to end
>
> the strfile method is plausible, but i'd much rather work with the
> file that i have rather than autogenerate another one. and the file i
> got doesn't have any %'s.
I found this beauty in perlfaq5:
How do I select a random line from a file?
Here's an algorithm from the Camel Book:
srand;
rand($.) < 1 && ($line = $_) while <>;
This has a significant advantage in space over reading the
whole file in. A simple proof by induction is available
upon request if you doubt the algorithm's correctness.
It is a sweet algorithm, and doesn't require you know the length of the
file in advance. The random line is in $line after the loop exits.
Steve
--
Steven Smolinski => http://arbiter.ca/
Reply to: