Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl merge hashes

Tags:

hash

perl

hashref

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 :)

like image 276
AkshaiShah Avatar asked Dec 29 '25 10:12

AkshaiShah


2 Answers

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',
   },
);
like image 101
ikegami Avatar answered Dec 30 '25 22:12

ikegami


If you use

$one{location} = \%two

then your hash will contain a reference to hash %two, so that if you modify it with something like $one{location}{newval} = 'goodbye' then %two will also be changed.

If you want a separate copy of the data in %two then you need to write

$one{location} = { %two }

after which the contents of %one are independent of %two and can be modified separately.

like image 27
Borodin Avatar answered Dec 31 '25 00:12

Borodin