Reputation: 31
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= {
'567' => 'A1',
'689' => 'A2',
}
There will be no missing elements in either structure and there will no 'undef' values either.
Upvotes: 0
Views: 456
Reputation: 386561
# 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;
}
Upvotes: 2
Reputation: 117871
You can create a temporary hash that you use for mapping between the two.
#!/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);
Upvotes: 2