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.
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"] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With