Reputation: 1773
Are there any syntax errors in the setup of the array of hashes? It didn't give any warnings, but I also cannot print an item, so I hope that the setup isn't the problem.
How can I access eg x
inside of list5
to print it?
.
use strict;
use warnings;
my (%list0, %list1, %list2, %list3, %list4, %list5);
%list5 = (
"list" => 5,
"x" => 1,
"y" => 1,
"z" => 0,
);
my @full_list = (%list0, %list1, %list2, %list3, %list4, %list5);
print ??
Upvotes: 0
Views: 84
Reputation: 6204
The elements of an array of hashes (AoH) are references to those hashes, so you need to populate @full_list
with hash references. Given your script, do the following:
my @full_list = \( %list0, %list1, %list2, %list3, %list4, %list5 );
Then, to access "x
inside of list5
":
print $full_list[5]->{x}; # prints 1
The ->
notation is the arrow operator, which dereferences the hash reference in $full_list[5]
.
To use list5
as the index into @full_list
, you can use the constant pragma:
use strict;
use warnings;
use constant list5 => 5;
...
print $full_list[list5]->{x}; # prints 1
Hope this helps!
Upvotes: 3
Reputation: 1166
Perhaps, this is helpful:
As you have it defined (@full_list = (%list0, %list1,...);), the dump of the @full_list via
use Data::Dumper;
print Dumper \@full_list;
looks like
$VAR1 = [
'y',
1,
'x',
1,
'z',
0,
'list',
5
];
where the even elements are your hash keys and the odd element following each is the value. What Kenosis described is probably what you want. But if for some reason, that is just given to you (in another form and you are simplifying it for us here) and you must work with @full_list or an array defined like that, you can get a hash back that consists of keys and values from all the initial hashes.
my %full_list_hash = @full_list;
print $full_list_hash{x};
Upvotes: 0