How do I add a new Key,Value pair to a Hash in an array of hash in perl?

11,364

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.

Share:
11,364
user1768233
Author by

user1768233

Updated on June 05, 2022

Comments

  • user1768233
    user1768233 almost 2 years

    Hi I have a 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 1 array entry) The output of the print statement just contains the 1 entry.

    my @AoH;
    push @AoH, { TEST1 => 'testvalue'  };
    for my $hash (@AoH)
    {
    $hash{'TEST2'} = 'testvalue2';
    print Dumper($hash);
    }
    

    What am I doing wrong?

    Thank you.

  • user1768233
    user1768233 over 10 years
    Thanks Dms, yeah it was done for the purpose of an example. I'm am using strict and warnings and I had tried dereferencing it but still no luck. I should be back home in a few hours, I'll try again and see how it goes.