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

((keys %hash)[int rand keys %hash]) You don't need scalar() because rand() automatically converts its argument to a scalar.

Replies are listed 'Best First'.
Re: Answer: How do I select a random key from a hash?
by merlyn (Sage) on Mar 25, 2001 at 19:14 UTC
    You also don't need int because indexing automatically int's it. {grin}

    But you are computing the keys twice, and that's expensive for large hashes. Perhaps this instead:

    do { my @k = keys %hash; $k[rand @k] }

    -- Randal L. Schwartz, Perl hacker

      scalar keys %hash doesn't actually compute the keys (except for tied hashes).