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.
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"] }
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.
my @arr = (
{ name => "aaa" , values => ["a1","a2"] },
{ name => "bbb" , values => ["b1","b2","b3"] }
);
Lists ( made with ()
) will get flattened. Arrayrefs ([]
) won't.
See perldoc perlreftut
for more.
Also, avoid using $a
and $b
as variable names as they are intended for special use inside sort
blocks.
精彩评论