0

对不起,如果我所说的哈希数组是别的东西。从现在开始,我将把这些东西称为“结构”。无论如何,假设我有两个结构:

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”值。

4

2 回答 2

2

您可以创建一个临时哈希,用于在两者之间进行映射。

#!/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);
于 2020-12-21T10:09:00.557 回答
2
# 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;
}
于 2020-12-21T11:44:21.077 回答