Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
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
  • Outside of code tags, you may need to use entities for some characters:
            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 having an uproarious good time at the Monastery: (10)
    As of 2014-09-23 12:23 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (220 votes), past polls