in reply to How do I efficiently predeclare a hash with a set of keys

This is concise and saves a little space by not allocating any to the values.* The keys however still exist and test as such with exists.

my %set; undef @set{ 5,6,8..53,62..106 };

Update: This used to make a difference at some point in the past, but it no longer does (circa. 5.8.8 and possibly before).

The null list assignment method others have described my %set; @set{ ... } = (); is equal in memory usage and actually slightly faster. Thanks to bart++ for bringing this to my attention.

If you haven't voted on this node yet, please downvote it.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^2: How do I efficiently predeclare a hash with a set of keys
by bart (Canon) on May 19, 2007 at 09:30 UTC
    How does this compare, for speed and memory use, to
    @set{ 5,6,8..53,62..106 } = ();
    ? I'd expect them to be comparable.

      Good call. At some point in the past, the undef version used less memory and was faster than the null list assignment version. If I remember correctly, it was tilly that pointed this out to me.

      However, I just tried it with 5.8.8 and that is no longer the case. They both use the same amount of memory, and the null list assignment is marginally (~4%) faster. It's still faster and uses less memory than the typical method.

      my %set = map{ $_ => 1 } 1, 2, 5..8, 100..200;

      Another case of How do I know what I 'know' is right?. :( I'll update my node above to reflect this.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: How do I efficiently predeclare a hash with a set of keys
by lupey (Monk) on May 18, 2007 at 19:42 UTC
    Thank you. This is exactly what I wanted :)