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 :)
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',
},
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With