Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
eran Avatar asked Dec 04 '22 20:12

eran


1 Answers

I want to have an array of hashs in perl

You can't. Arrays only contain scalars in Perl. However, {} will create a hashref, which is a scalar and is fine.

But this:

{ name => "aaa" , values => ("a1","a2") }

means the same as:

{ name => "aaa" , values => "a1", "a2" },

You want an arrayref (which is a scalar), not a list for the value.

{ name => "aaa" , values => ["a1","a2"] }
like image 107
Quentin Avatar answered Dec 07 '22 09:12

Quentin