Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

How do I select a random key from a hash?

( #56423=categorized question: print w/ replies, xml ) Need Help??
Contributed by tadman on Feb 05, 2001 at 20:41 UTC
Q&A  > hashes

Answer: How do I select a random key from a hash?
contributed by mirod

The brute force solution:

/bin/perl -w use strict; my %h=( k1 => "v1", k2 => "v2", k3 => "v3"); my @keys= keys %h; my $k= $keys[int rand( @keys)]; print "random key: $k\n";'

If you want to do this on a huge hash and you want to do lots of random access and updates then you should look at Building a Better Hash, a pretty clever way to solve this problem.

Answer: How do I select a random key from a hash?
contributed by arhuman

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.]
Answer: How do I select a random key from a hash?
contributed by MrNobo1024

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

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others avoiding work at the Monastery: (11)
    As of 2016-02-08 13:22 GMT
    Find Nodes?
      Voting Booth?

      How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

      Results (276 votes), past polls