Search code examples
perlhash

Add multiple values to an already existing hash


I have the following hash, and I want to add more values to it; however, doing it replaces the entire hash. I'm pretty sure this is a basic level question, but perl is an enigma wrapped in a mystery.

my %myNewHash = ();

%myNewHash = (
    lastName => $primaryInfo->{lastName},
    firstName => $primaryInfo->{firstName}
);

%myNewHash = (
    email => $primaryInfo->{email},
    phone => $primaryInfo->{phone}
);

At this point, %myNewHash only contains email/phone, lastName/firstName have been wiped out.


Solution

  • Existing hash (note that you don't need create an empty hash before assigning to it):

    my %myNewHash = (
        lastName => $primaryInfo->{lastName},
        firstName => $primaryInfo->{firstName}
    );
    

    Since you're using the same keys in the new and the old hashes:

    $myNewHash{$_} = $primaryInfo->{$_} for qw(email phone);
    

    Or with a hash slice:

    my @keys = qw(email phone);
    @myNewHash{@keys} = @{ $primaryInfo }{@keys};
    

    The key (pun intended) is that you assign to an individual element

    $hash{key} = ...
    

    instead of to the hash itself

    %hash = ( ... );