将多个值添加到现有哈希

时间:2013-12-24 22:57:50

标签: perl hash

我有以下哈希,我想为它添加更多值;但是,这样做会取代整个哈希值。我很确定这是一个基本的问题,但是perl是一个神秘的谜。

my %myNewHash = ();

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

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

此时,%myNewHash仅包含电子邮件/电话,lastName / firstName已被删除。

4 个答案:

答案 0 :(得分:6)

现有哈希(请注意,在分配给它之前不需要创建空哈希):

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

因为您在新旧哈希中使用相同的键:

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

或使用哈希切片:

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

密钥(双关语)是您分配给单个元素

$hash{key} = ...

而不是哈希本身

%hash = ( ... );

答案 1 :(得分:3)

这是你可以做到的一种方式:

use strict;
use warnings;

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

$myNewHash{email} =  $primaryInfo->{email};
$myNewHash{phone} =  $primaryInfo->{phone};

或者:

use strict;
use warnings;

my %myNewHash;
$myNewHash{lastName}  =  $primaryInfo->{lastName};
$myNewHash{firstName} =  $primaryInfo->{firstName}
$myNewHash{email}     =  $primaryInfo->{email};
$myNewHash{phone}     =  $primaryInfo->{phone};

答案 2 :(得分:3)

每当你这样做:

%myNewHash = ...;

您正在重新初始化%myNewHash的值。这就是=运算符的作用。它与以下内容相同:

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

要解决此问题,您可以执行以下操作:

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

在此上下文中,%myNewHash中的键/值对被视为一个数组,另外两个键/值对被放入该数组并作为一个大数组分配给%myNewHash%myNewHash已重新初始化,但现在包含之前的退出键/值对。

我个人不会这样做,因为它不是100%清楚发生了什么。如果您想将哈希引用转换为哈希,您可以取消引用它并一次性完成所有操作:

my %myNewHash = %{ $primaryInfo };  # Easy to understand.

或者使用循环来选择要传输的几个键:

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

我确信甚至有办法使用map,但我无法想到它。

答案 3 :(得分:0)

尝试像这样添加:

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