in reply to How do I select a random key from a hash?

What's wrong with this ?:
$lh=scalar keys %h; print ((keys %h)[int rand($lh)]);
[Q&A Editor- Changed '(split "/",scalar %h)[0]' to "scalar keys %h" as noted by chipmunk.]

Replies are listed 'Best First'.
Re: Answer: How do I select a random key from a hash?
by chipmunk (Parson) on Feb 05, 2001 at 22:01 UTC
    In a scalar context, %h returns a string consisting of the number of buckets used, a slash, and the number of buckets allocated. You could have a hash with 1000 keys and only 16 buckets. Thus, your "random key" is limited to one of the first few keys in the hash.

    Try $lh = scalar keys %h; instead.