Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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!
  • 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?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others cooling their heels in the Monastery: (5)
    As of 2015-07-06 04:35 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









      Results (70 votes), past polls