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



如果我所调用的哈希数组是其他东西,那么很抱歉。从现在起,我将把这些东西称为"结构"。无论如何,假设我有两个结构:

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;
}

相关内容

  • 没有找到相关文章

最新更新