I have a large hash that I am using to cache an even larger number of data items.

When I need to add a new cache item, and the cache is full, I use 'each %hashCache' to select a "random" (key, value) pair which I then delete using 'delete($hashCache{$key})'

However, every once in a while, I get an error message:

 Use of uninitialized value $key in delete...

even though there are clearly still keys in the hash. If however, after every delete, I do something like '$mycount=keys(%hashCache)' then the error doesn't occur.

Thus it seems like unless I do something to tell perl to recalculate the keys, 'each' ends up sometimes giving up the same key that I had previously deleted. Is this a bug, limitation, or feature in the implementation of 'each' and/or how hash memory is cleaned up after 'delete'? (or am I truly missing something obvious).


In reply to Using 'each' to get random (key, value) pair from hash returns "uninitialized value" by puterboy

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.