Search code examples
arraysperlhashperl-data-structures

How do I append a new hash to an array of hashes?


If I wanted to add a new hash to all the arrays in the mother_hash using a loop, what would be the syntax?

My hash:

my %mother_hash = (
    'daughter_hash1' => [ 
        { 
          'e' => '-4.3', 
          'seq' => 'AGGCACC', 
          'end' => '97', 
          'start' => '81' 
        } 
    ],
    'daughter_hash2' => [ 
        { 
          'e' => '-4.4', 
          'seq' => 'CAGT', 
          'end' => '17', 
          'start' => '6' 
        }, 
        { 
          'e' => '-4.1', 
          'seq' => 'GTT', 
          'end' => '51', 
          'start' => '26' 
        }, 
        { 
          'e' => '-4.1', 
          'seq' => 'TTG', 
          'end' => '53', 
          'start' => '28' 
        } 
    ],
    #...
);

Solution

  • If you have a hash of arrays of hashes and want to add a new hash to the end of each of the arrays, you can do:

    push @{ $_ }, \%new_hash for (values %mother_hash);
    

    This loop iterates over the values of %mother_hash (which are array refs in this case) and setting $_ for each iteration. Then in each iteration, we push the reference to the new hash %new_hash to the end of that array.