Reputation: 1461
I need to add a new key-value pair to the hash entries within an array of hashes. Below is some sample code which does not work (simplified with only one array entry).
The output of the print statement just contains the same one entry.
my @AoH;
push @AoH, { TEST1 => 'testvalue' };
for my $hash (@AoH)
{
$hash{'TEST2'} = 'testvalue2';
print Dumper($hash);
}
What am I doing wrong?
Upvotes: 6
Views: 17694
Reputation: 817
This code looks a little strange, so I am going to assume it was done like that for the purposes of showing it briefly here, but the main thing you need to do to fix your code is change:
$hash{'TEST2'} = 'testvalue2';
to:
$$hash{'TEST2'} = 'testvalue2';
or:
$hash->{'TEST2'} = 'testvalue2';
The extra $
or ->
dereferences the hash reference $hash
. Since neither is there, it treats $hash{'TEST2'}
as a different variable: %hash
(not $hash
) and assigns testvalue2
to that. You would have gotten a good error message:
Global symbol "%hash" requires explicit package name at - line XX
if you tried to run this code with:
use strict;
use warnings;
at the beginning... which you should always do, so do that every time from now on.
Upvotes: 9
Reputation: 1820
use strict;
use warnings;
use Data::Dumper;
my @AoH=();
my %data_source_hash=(
TEST1 => 'testvalue1',
TEST2 => 'testvalue2'
);
# adds whole hash as the array element
push @AoH,{ %data_source_hash };
print Dumper(@AoH);
@AoH=();
print "---------------------------\n";
# adds each hash $key, $value pair as an element
while ( my ($key, $value) = each %data_source_hash )
{
push @AoH, { $key => $value };
}
print Dumper(@AoH);
@AoH=();
print "---------------------------\n";
# adds extra hash entry to each array element
push @AoH, { TEST1 => 'testvalue' };
push @AoH, { TEST3 => 'testvalue3' };
foreach my $el (@AoH)
{
my $key = 'TEST2';
$$el{$key} = $data_source_hash{$key};
}
print Dumper(@AoH);
Upvotes: 0