用其他两个哈希值构建哈希值?

时间:2014-03-11 09:19:13

标签: perl hash

我有两个具有相似键但值不同的哈希值。

我想构建第三个哈希,其中包含第一个哈希的所有键和第二个哈希的所有值。

如果第二个哈希没有任何给定键的元素,那么结果哈希的对应值应为空或undef

例如,使用这些哈希

my %hash1 = (
  BLUE   => 30,
  GREEN  => 40,
  INDIGO => 12,
  ORANGE => 56,
  RED    => 45,
  VIOLET => 25,
  YELLOW => 10,
);

my %hash2 = (
  BLUE   => ["command1", "command2", "command3", "command4"],
  GREEN  => ["Windows", "Linux", "Unix", "Mac"],
  INDIGO => ["Air", "Earth", "Sky", "Water", "Fire"],
  RED    => ["physics", "chemistry", "biology"],
  YELLOW => ["Apple", "Orange"],
);

我想制作这个

my %hash3 = (
  BLUE   => ["command1", "command2", "command3", "command4"],
  GREEN  => ["Windows", "Linux", "Unix", "Mac"],
  INDIGO => ["Air", "Earth", "Sky", "Water", "Fire"],
  ORANGE => [],
  RED    => ["physics", "chemistry", "biology"],
  VIOLET => [],
  YELLOW => ["Apple", "Orange"],
);

我正在尝试的代码如下,但它会引发错误。你能否确定我遗失的内容?

foreach my $key (keys %hash1) {
  push @{$hash3{$key}} @{$hash2{$key}};
}

3 个答案:

答案 0 :(得分:3)

push的参数之间缺少逗号。

push @{$hash3{$key}}, @{$hash2{$key}};

答案 1 :(得分:2)

你需要的只是

my %hash3 = map { $_ => $hash2{$_} } keys %hash1;

%hash获取每个密钥,并将其与%hash2中的相应值配对,形成%hash3。访问%hash2中不存在的元素将返回undef而无需其他代码。

<强>输出

(
  BLUE   => ["command1", "command2", "command3", "command4"],
  GREEN  => ["Windows", "Linux", "Unix", "Mac"],
  INDIGO => ["Air", "Earth", "Sky", "Water", "Fire"],
  ORANGE => undef,
  RED    => ["physics", "chemistry", "biology"],
  VIOLET => undef,
  YELLOW => ["Apple", "Orange"],
)

<强>更新

您要求&#34;空白或取消定义&#34; 以查找%hash3%hash2没有值的值my %hash3 = map { $_ => $hash2{$_} // [] } keys %hash1; ,但您请求的结果显示空匿名而是数组。要实现这一点,您只需将代码更改为

即可
(
  BLUE   => ["command1", "command2", "command3", "command4"],
  GREEN  => ["Windows", "Linux", "Unix", "Mac"],
  INDIGO => ["Air", "Earth", "Sky", "Water", "Fire"],
  ORANGE => [],
  RED    => ["physics", "chemistry", "biology"],
  VIOLET => [],
  YELLOW => ["Apple", "Orange"],
)

给出了这个输出

{{1}}

答案 2 :(得分:0)

我刚刚编写了以下代码,但它确实有效。

foreach my $key (keys %hash1) {
    if (exists ($hash2{$key})) {
        push @{$hash3{$key}}, @{$hash2{$key}};
    }
    else {
         $hash3{$key} = [ ];
    }
}
相关问题