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

Hi, I am trying to build a hash of arrays from a list from a file that contains groups of strings (ie:
GroupA, 123a
GroupB, 222c
GroupA, 456d
GroupB, 456s
)
In this way I can group the strings, then use them as an array elsewhere. I am planning to push the strings into the hash of arrays this way:
  push(@{$hash{$key}}, $insert_val); (I picked this off of: http://www.perlmonks.org/?node_id=1977)

However, how do I declare and initialize this %hash before I can use it in the push above?

Thanks in advance.

Replies are listed 'Best First'.
Re: How to declare a hash of array?
by rhesa (Vicar) on Sep 29, 2007 at 09:09 UTC
    That's easy, just declare it:
    my %hash;
    Perl will take care of the rest: it will create new keys on demand, and it'll also create the arrays on the fly. This process is called Autovivification.
      But careful with mixed data structures and the risk of accidental symbolic references. strict can catch that.

      An example:

      my %hash; $hash{beta} = 'x'; for my $name ( qw(alpha beta) ) { push @{$hash{$name}}, 123, 456; } use Data::Dumper; print Dumper \%hash;
      Result:
      $VAR1 = { 'alpha' => [ 123, 456 ], 'beta' => 'x' };
      So... where's the array data for 'beta'? It's in the global variable @x. Witness: append this line to the above script:
      print Dumper \@x;
      Result:
      $VAR1 = [ 123, 456 ];

      With strict enabled, it'll get caught while trying to push the data: insert the line

      use strict;
      at the top of the script and comment out the line, dumping @x, we appended earlier:
      Can't use string ("x") as an ARRAY ref while "strict refs" in use at t +est.pl line 6.

      Nasty if you didn't expect it.

      The risk of running into it is greatest when using data structures of unequal depth.

Re: How to declare a hash of array?
by johnlawrence (Monk) on Sep 29, 2007 at 09:18 UTC
Re: How to declare a hash of array?
by perlfan (Parson) on Sep 29, 2007 at 14:29 UTC
    You don't have to initialize hash members. Doing the following will work as long as $hash, $key, and $insert_value are initialized themselves:
    #!/user/bin/env perl use strict; use warnings; use Data::Dumper; my %hash = (); my $key = 'A'; my $insert_value = 123; push(@{$hash{$key}},$insert_value); print Dumper(\%hash);
    Output:
    $VAR1 = { 'A' => [ 123 ] };
Re: How to declare a hash of array?
by throop (Chaplain) on Sep 29, 2007 at 20:38 UTC
    Since others have answered your questions, here's some hints on linking.

    You wrote

    (I picked this off of: http://www.perlmonks.org/?node_id=1977)
    Typing in the following pseudo-HTML will automagically generate hyperlinks:
    I picked this up [1977|here].<br> I picked this up from [How do I make a hash of arrays?]
    as
    I picked this up here.
    I picked this up from How do I make a hash of arrays?
    throop