I did some more meditation and research...

First of all I have to say, that I can't possibly see why one would want to store a "representative key" of a hash in another structure (like the OP did)

Unless you want only to check if the hash is populated, then

DB<129> scalar %empty => 0

will do the trick without side effects ( scalar keys %empty would reset the iterator).

Also the usual trick to copy a hash before iterating (in order to protect the iterator) is far slower than assigning to a one element list (which can't compete with each)

DB<100> $h{$_}=$_ for 1..5e6 DB<101> $t=time; %h2=%h; print time-$t; 124 DB<102> $t=time; ($k)=%h; print time-$t; 19 DB<103> use Time::HiRes qw(time) DB<104> $t=time; ($k)=each %h; print time-$t; 7.70092010498047e-05

BUT I have to say I'm very critical about hashes of that size, because memory consumption can easily freeze your system.¹

Depending on use case I'd either consider using a database or a hash of hashes (of hashes ...) which is far more "swap friendly".

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

¹) even emptying a hash with 5e6 entries can take minutes on a netbook.


In reply to Re^3: Preventing unintended list expansion inside hash literals. by LanX
in thread Preventing unintended list expansion inside hash literals. by gregory-nisbet

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.