in reply to •Re: selecting random key from hash
in thread selecting random key from hash

You could also use a variation on the random line from a file FAQ:

my( $key, $val ); my $ctr = 0; while( my( $k, $v ) = each %hash ) { rand( $ctr++ ) < 1 && do { $key = $k; $val = $v }; }

Actually merlyn's is more efficient since it only reads up to the "victim" element, whereas this would hit all elements (which it has to for the original random line from a file version). Then again if this is a tied hash and FETCH had side-effects that might be what you want. At any rate see perldoc -q "random line" for more info.

Replies are listed 'Best First'.
•Re^3: selecting random key from hash
by merlyn (Sage) on Jul 13, 2004 at 03:20 UTC
    Yeah, I actually thought of that first, and then discounted it for the reasons you mentioned. The big difference is that for the random-line solution, we have no cheap way of determining the entire set size, where with a hash, scalar-keys is cheap and tells us what we need to know.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.