Search code examples
arraysperlhashpopulateperl-data-structures

Populate hash of hashes in Perl


I want to know how to populate the following hash structure:

my $hash = {
    'user' => [
        {
            'id' => '1',
            'name' => 'John'
        },
        {
            'id' => '2',
            'name' => 'Pat'
        }

    ]
};

I want to be able to dynamically populate this hash. I want to loop around values from my database and push (add) new values (id, name) in order to populate the hash.


Solution

  • In order to populate a value in a hash of hashes, one can just use :

    my %hash;
    ....
    $hash{$key}{$subkey} = $value;
    

    Be careful when you loop through them, however! The scalar value $hash{$key} will actually be a scalar reference to the sub-hash, not the sub-hash object itself.