in reply to Re: multiple values for one key in hash
in thread multiple values for one key in hash

Note: you have to create the anonymous reference -- you can't just push a value if the key doesn't exist.

In perl you can ;-)

use strict; use warnings; use Data::Dumper; my %hash; push @{$hash{key}}, 'value'; print Dumper \%hash; __END__ $VAR1 = { 'key' => [ 'value' ] };

This nice feature is called "autovivification" and is quite useful most of the time.

Replies are listed 'Best First'.
Re^3: multiple values for one key in hash
by wade (Pilgrim) on May 12, 2008 at 22:46 UTC

    Son of a gun! You can just push the value. I could have sworn that this didn't work when I tried it at my old job (about 2 years ago). Is this a feature that has happened since then or have I been brain dead all this time?

    Thanks, moritz; ++

    --
    Wade
      It doesn't work if there was an undef explicitly assigned to the value before. A lot of people get tripped up by this because they just assign undef to something they don't use anymore instead of deleting the key.

      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

        How would autovivification know that the undef in lvalue context it's autovivifying wasn't the original undef?

        $ perl -MYAML::Syck -le '$h{bar}=1;$h{bar}=undef;push @{$h{bar}}, qw/a + b c/;print Dump( \%h )' --- bar: - a - b - c

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.