Whenever you do:
%myNewHash = ...;
You're reinitializing the value of %myNewHash. This is what the =
operator does. It's the same thing as:
my $var = "This is the first part of my sentence,";
my $var = " and this is the last part of my sentence."; # Reinitializing $var, not appending it
To get around this, you could do the following:
%myNewHash = ( %myNewHash, email => $primaryInfo->{email}, phone => $primaryInfo->{phone} );
In this context, the key/value pairs in %myNewHash
are treated as an array, The other two key/value pairs are put into that array and assigned to %myNewHash
as one big array. %myNewHash
is reinitialized, but now contains the exiting key/value pairs it had before.
I personally wouldn't do this because it's not 100% clear what's going on. If you want to convert your hash reference into a hash, you can dereference it and do it all in a single shot:
my %myNewHash = %{ $primaryInfo }; # Easy to understand.
Or use a loop to pick off the few keys you want to transfer over:
for my $key ( qw( email phone ) } {
$myNewHash{$key} = $primaryInfo->{$key};
}
I'm sure there's even a way to use map
, but I can't think of it right off hand.