Search code examples
perlperl-data-structures

how to have hash of list in perl


Sorry for this syntax question. I fail to find the solution. I want to have an array of hashs in perl, each of them has string and array. I'm trying to write the following code:

use strict;
my @arr = (
       { name => "aaa" , values => ("a1","a2") },
       { name => "bbb" , values => ("b1","b2","b3") }
      );


foreach $a (@arr) {
  my @cur_values = @{$a->{values}};
  print("values of $a->{name} = @cur_values\n");
};

But this does not work for me. I get compilation error and warning (using perl -w)

Odd number of elements in anonymous hash at a.pl line 2. Can't use string ("a1") as an ARRAY ref while "strict refs" in use at a.pl line 9.


Solution

  • Try the following:

    use strict;
    my @arr = (
           { name => "aaa" , values => ["a1","a2"] },
           { name => "bbb" , values => ["b1","b2","b3"] }
          );
    
    
    foreach $a (@arr) {
      my @cur_values = @{$a->{values}};
      print("values of $a->{name}: ");
        foreach $b (@cur_values){
            print $b . ", "
        }
        print "\n";
    };
    

    You just needed to use square brackets when defining your array on lines 3 and 4.