Search code examples
perlhashhashref

Perl merge hashes


Is it possible to merge two hashes like so:

%one = {
    name    => 'a',
    address => 'b'
};

%two = {
    testval => 'hello',
    newval  => 'bye'        
};

$one{location} = %two;

so the end hash looks like this:

%one = {
    name    => 'a',
    address => 'b',
    location => {
        testval => 'hello',
        newval  => 'bye'
    }
}

I've had a look but unsure if this can be done without a for loop. Thanks :)


Solution

  • One can't store a hash in a hash since the values of hash elements are scalars, but one can store a reference to a hash. (Same goes for storing arrays and storing into arrays.)

    my %one = (
       name    => 'a',
       address => 'b',
    );
    
    my %two = (
       testval => 'hello',
       newval  => 'bye',     
    );
    
    $one{location} = \%two;
    

    is the same as

    my %one = (
       name    => 'a',
       address => 'b',
       location => {
          testval => 'hello',
          newval  => 'bye',
       },
    );