Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to define a hash with keys whose values are undef.

Of course, I can just do 'key' => undef, etc... but this becomes tedious when you have a bunch of keys.

I want to do this when I am declaring the hash, and not afterwards. How can I do this when I first declare the hash without having to do 'key' => undef, for each key/value pair?

Thank you Monks.

  • Comment on How to create a hash whose values are undef?

Replies are listed 'Best First'.
Re: How to create a hash whose values are undef?
by GrandFather (Saint) on Jul 06, 2009 at 03:13 UTC

    You may like:

    my %hash = map {$_ => undef} @keys;

    or:

    my $hashRef = {foo => {map {$_ => undef} @keys}};

    for the nested key hash ref version.


    True laziness is hard work
Re: How to create a hash whose values are undef?
by roubi (Hermit) on Jul 06, 2009 at 02:35 UTC
    Assuming your keys are in @keys:
    my %hash; @hash{@keys} = ();
      But what if I want @keys to be the keys in a second-level hash, like so:

      $hash = {'foo' => { 'key1 => undef, 'key2' => undef, ...
      I am using a hash ref here, but I don't think that should make too much of a difference.
Re: How to create a hash whose values are undef?
by missingthepoint (Friar) on Jul 06, 2009 at 05:25 UTC

    Thanks GrandFather :)


    Ca3n w2e ple6ase st4op doi5ng th4is?
Re: How to create a hash whose values are undef?
by Anonymous Monk on Jul 06, 2009 at 03:17 UTC
    Thank you everyone!!
      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.