Reputation: 465
I am trying to access elements of an array of hashes.
This is a dump of my variable $tst
[
{ DESCRIPTION => "Default", ID => 0, NAME => "Default", VERSION => "1.0" },
{ DESCRIPTION => "", ID => 1, NAME => "Custom 1", VERSION => "1.1" },
{ DESCRIPTION => "", ID => 2, NAME => "Custom 2", VERSION => "1.0" },
{ DESCRIPTION => "", ID => 3, NAME => "Custom 3", VERSION => "6.0" },
{ DESCRIPTION => "", ID => 4, NAME => "Custom 4", VERSION => "1.0" },
]
I am trying to access the values for the elements. For example if the ID is 4 then return the field NAME
.
I tried printing all of the values for ID
but it hasn't been working.
I used variations of the Perl code below from looking online
foreach ($tst) {
print "$_->{'ID'}, \n";
}
And it gives the following error:
Not a HASH reference at file.pl line 22.
Note: line 22 is the print
line from above.
Upvotes: 0
Views: 332
Reputation: 126722
The answer that you have accepted is correct, but your data structure is such that you can index the array by the ID value. That is to say $tst->[$id]{ID} == $id
for all elements.
So, to print the NAME
field for the ID
4 you can say
print $tst->[4]{NAME}, "\n";
and you will see
Custom 4
I hope this helps.
Upvotes: 3
Reputation: 1106
You first have to dereference the array of hash. So,
foreach (@$tst) {
print $_->{ID}, "\n";
}
should print all the IDs.
Upvotes: 5