I need a random element from a huge hash, one large enough that using keys to get a list of elements cripples my system. (Why didn't I use an array? I didn't plan to have to do this, and most of what I'm doing with this thing involves pulling single records by name.)

I looked at the answers at Pulling random elements from a hash, but they involve the keys method too. I'm thinking what I'm going to do, since this only needs to run once, is iterate through once using each to find the total number of elements, generate unique random numbers in that range, and then iterate through again, grabbing those records as I go.

This seems gross, but I backed myself into the corner of having to do it. I was wondering, though, if some of the minds here had a cleaner solution.

Side question: perldoc states that, for a given run of perl and an unmodified hash, each, keys, and values are guaranteed to have the same ordering as each other. What about repeated iterations of the same type? For example, if I use keys, process the results without changing the hash, and then use keys again, do I get the same ordering? My testing says yes, but is it guaranteed?


In reply to Random hash element (low memory edition). by amarquis

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.