in reply to How to create a hash whose values are undef?

Thank you everyone!!
  • Comment on Re: How to create a hash whose values are undef?

Replies are listed 'Best First'.
Re^2: How to create a hash whose values are undef?
by Marshall (Canon) on Jul 06, 2009 at 05:31 UTC
    Great that you have figured out "how" to do it. My question is "why"?.

    Perl has the ability to automatically bring a new key into existence when you assign something to it without the need for that key to have been created beforehand - this is true in n-dimensional hash structures also. So in many situations, there is no need to make an "undef" value for a key or even to create that key. Sometimes there is a need ("in many situations" does definitely not mean "in all situations").

    I am just curious as to why you want to do this?

    Update: I am not saying that anything in the other posts is wrong - quite the contrary - there are some excellent formulations of how to do this. Grandfather's stuff looks fantastic to me. I'm just saying that often it is not necessary to set a whole bunch of keys to "undef" in the first place. Maybe in this application it is warranted. But if its not needed, then there can be some simplifications.

      If you want to initialise the values to some other value, say zero, for example:
      my %hash; @hash{@keys} = (0) x @keys;
      The LHS is a slice, on the RHS the value, 0, is in parentheses which generates a list, the @keys is used in scalar context to get the correct number of values.
        Great! I like your thinking, but you should be aware that "0" and even "" is not the same as "undef".
        #!/usr/bin/perl -w use strict; use Data::Dumper; my @keys = (1,2,3); my %hash; @hash{@keys} = (undef) x @keys; print Dumper \%hash; __END__ Prints: $VAR1 = { '1' => undef, '3' => undef, '2' => undef };