Reputation: 5939
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 :)
Upvotes: 2
Views: 442
Reputation: 126722
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.
Upvotes: 3
Reputation: 385655
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',
},
);
Upvotes: 6