The fact that it looks more like you should be using an array notwithstanding, I'll go ahead and answer the question asked in the subject line anyway:

Here is one way to select a single random element from a hash:

my $randelement = ( keys %hash )[ rand( scalar keys %hash ) ];

This works by creating a list of the keys, and then by generating a random number between zero and n, where n is the number of keys. Using keys in scalar context is an efficient way of determing the number of keys in the hash. That random number is then used as a list index (like an array index) to grab the element corresponding with that random index number. The fact that rand generates floating point numbers doesn't matter; array and list indices are implicitly truncated to integers. That also means that 10.999 will be the element number 10, which is the 11th element. And 0.999 will be element number 0, the 1st element.

If you're going to be grabbing several elements, and don't want to repeat, use a Fisher Yates shuffle, from List::Utils and then iterate over the list.


Dave


In reply to Re: Select randomly from a hash by davido
in thread Select randomly from a hash by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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.