in reply to Re: Random hash element (low memory edition).
in thread Random hash element (low memory edition).

That method is awfully neat, but my perl skills are not so I'll hit you with a follow-up question.

rand($.) < 1 && ($line = $_) while <>;

So this iterates through the file and, if a random number from 0 to the current line number is less than 1, selects the current line, overwriting previous choices? So, in my case, I'd just keep a count variable for how many elements I've been through and use that in place of $.?

I'm going to have to check out the proof of that, it is really interesting that everything evens out (i.e. the first elements have a high chance of being overwritten, the latter elements have a high chance of just not being picked, and it all balances out to a random selection.) Thanks for pointing me to that FAQ entry!

Replies are listed 'Best First'.
Re^3: Random hash element (low memory edition).
by Roy Johnson (Monsignor) on Jan 24, 2008 at 21:06 UTC
    So, in my case, I'd just keep a count variable for how many elements I've been through and use that in place of $.?

    Exactly.


    Caution: Contents may have been coded under pressure.