Perl:组合两个散列数组的值并使第二个数组的值成为输出散列的键

Perl: Combining the values of two arrays of hashes and making the values of the second array the keys of the output hash

抱歉,如果我所说的散列数组是别的东西。从现在开始,我将把这些东西称为 'structures'。 无论如何, 假设我有两个结构:

my @arrayhash;
push(@arrayhash, {'1234567891234' => 'A1'});
push(@arrayhash, {'1234567890123' => 'A2'});

my @arrayhash2;
push(@arrayhash2, {'1234567891234' => '567'});
push(@arrayhash2, {'1234567890123' => '689'});

如何获得输出:

@output= {
  '567' => 'A1',
  '689' => 'A2',
}

两个结构中都不会缺少元素,也不会有 'undef' 个值。

您可以创建一个临时散列,用于两者之间的映射。

#!/usr/bin/perl

use strict;
use warnings;

my @arrayhash;
push @arrayhash, {'1234567891234' => 'A1'};
push @arrayhash, {'1234567890123' => 'A2'};

my @arrayhash2;
push @arrayhash2, {'1234567891234' => '567'};
push @arrayhash2, {'1234567890123' => '689'};

my %hash; # temporary hash holding all key => value pairs in arrayhash
foreach my $h (@arrayhash) {
    while( my($k,$v) = each %$h) {
        $hash{$k} = $v;
    }
}

my %output;
foreach my $h (@arrayhash2) {
    while( my($k,$v) = each %$h) {
        $output{$v} = $hash{$k};
    }
}

my @output=(\%output);
# Build $merged{$long_key} = [ $key, $val ];
my %merged;
for (@arrayhash2) {
   my ($k, $v) = %$_;
   $merged{$k}[0] = $v;
}   

for (@arrayhash) {
   my ($k, $v) = %$_;
   $merged{$k}[1] = $v;
}

my %final = map @$_, values(%merged);

# Build $lookup{$long_key} = $key;
my %lookup;
for (@arrayhash2) {
   my ($k, $v) = %$_;
   $lookup{$k} = $v;
}   

my %final;
for (@arrayhash) {
   my ($k, $v) = %$_;
   $final{ $lookup{$k} } = $v;
}