in reply to duplicate keys on hash

Furthermore, Perl has a neat feature called, of all things, “autovivification” which makes this sort of thing very easy to express.   For example:

my $hash = {}; push @{$hash->{'foo'}}, 'bar';
... will in one step create a hash-key for 'foo' if it does not yet exist, and cause that bucket to contain an arrayref, and to push 'bar' onto that array.   So, in just one step, “the right thing” happens.

Each element of the resulting hash will therefore contain an arrayref, even if that arrayref contains only one entry.   In this way, an arbitrary number of values may be stored.   The same auto-vification trick can be used to construct other structures, as well.


Edited to fix the braces.

Replies are listed 'Best First'.
Re^2: duplicate keys on hash
by choroba (Cardinal) on Feb 11, 2015 at 13:18 UTC
    Please, test your code before posting.
    Scalar found where operator expected at - line 2, near "@($hash" (Missing operator before $hash?) Useless use of push with no values at - line 2. syntax error at - line 2, near "@($hash" Execution of - aborted due to compilation errors.

    Dereference uses curly brackets, not the round ones.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Oops.