On Mon, 19 Feb 2001, Bret Hughes wrote:
> Johannes Eriksson wrote:
> >
>
>
> > perl -e 'rand;rand($.)<1&&($l=$_)while<>;print $l;' < file
> >
> > It works. Believe me.
>
> i believe you. I just can't figure out what it is doing? I have been
> working with perl lately and always looking to learn. Can you explain
> what it is doing please?
ah, yes, the old "pick a random line from a file" trick. this is
explained in detail on pp. 284-285 of the "Perl Cookbook".
in a nutshell, it allows you to pick a random line from a file
without having the entire file in memory at once. (if you plan
on picking many, many random lines, one at a time, you're much
better off to just read in the entire file and treat it as an
array. the above trick assumes it's such a large file, you
can't do this.)
one line at a time, you read the next line using the "while <>"
construct. at the same time, the current line number will be in
the special variable $., and with probability 1/(line number),
this becomes your new random line. see the construct
rand($.) < 1 && ($l = $_)
all this says is, choose a random floating-point value in the
interval [0, $.). the chance of that value being less than 1 is,
in fact, 1 out of $. that's the probability that the line you
just read in becomes the *new* random line in the set of random
lines you're reading in. once you're finished reading the entire
file, $l will contain a randomly-selected line from that file.
piece of cake.
rday
--
Robert P. J. Day
Eno River Technologies, Durham NC
Unix, Linux and Open Source training
"This is Microsoft technical support. How may I misinform you?"
_______________________________________________
Redhat-list mailing list
[EMAIL PROTECTED]
https://listman.redhat.com/mailman/listinfo/redhat-list