简体   繁体   English

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

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

Sorry if what I'm calling array of hashes is something else.对不起,如果我所说的哈希数组是别的东西。 I'll just refer to these things as 'structures' from now on.从现在开始,我将把这些东西称为“结构”。 Anyways, Let's say I have two structures:无论如何,假设我有两个结构:

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

and

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

How can I get the output:如何获得 output:

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

There will be no missing elements in either structure and there will no 'undef' values either.两个结构中都不会缺少元素,也不会有“undef”值。

You can create a temporary hash that you use for mapping between the two.您可以创建一个临时 hash 用于两者之间的映射。

#!/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);

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM