如何合并哈希数组中的哈希

时间:2020-10-27 13:48:57

标签: perl

输入数组:

my @input = (
    {
        Id => 1,
        A => "abcd",
        B => undef,
        C => "rtyt"
    },
    {
        Id => 1, 
        A => undef,
        B => "efgh", 
    },
    {
        Id => 2,
        A => "ifk",
        B => "rjot",
    },
);

所需的输出:

my @output = (
    {
        Id => 1,
        A => "abcd",
        B => "efgh",
        C => "rtyt"
    },
    {
        Id => 2,
        A => "ifk",
        B => "rjot",
    },
);

我在这里看到的其他解决方案要么包含第一个哈希值,要么包含第二个哈希值的额外值,但我都需要。

1 个答案:

答案 0 :(得分:3)

哈希非常适合对事物进行分组。

# Keep first value in case of conflict.
my %by_id;
for my $rec (@input) {
   my $id = $rec->{Id};
   for my $k (keys(%$rec)) {
      $by_id{$id}{$k} //= $rec->{$k};
   }
}

# Keep last value in case of conflict.
my %by_id;
for my $rec (@input) {
   my $id = $rec->{Id};
   $by_id{$id} //= { %$rec };
   for my $k (keys(%$rec)) {
      if (defined($rec->{$k})) {
         $by_id{$id}{$k} = $rec->{$k};
      }
   }
}

以上构建

my %by_id = (
    "1" => {
        Id => 1,
        A => "abcd",
        B => "efgh",
        C => "rtyt",
    },
    "2" => {
        Id => 2,
        A => "ifk",
        B => "rjot",
    },
);

然后,我们可以简单地提取值。

my @output = @by_id{
   sort { $a <=> $b }
      keys(%by_id)
};