0

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.

You Idjit
  • 31
  • 4
  • Can your hashes contain more then one key value pair? are hashes added to the array in the same order I.E if i find hash with key xyz in index 5 of the array, am i assured that the same key xyz will be in index 5 of array 2? or are they ordered differently? – Chris Doyle Dec 21 '20 at 09:58
  • Yes, both hashes will have multiple (and equal number) of key value pairs but the order is not a given. – You Idjit Dec 21 '20 at 10:04
  • Ok thanks and is each key assured to occur only once? is it possible that key xyz may occur in more than one hash in the array? if so what should be the rule to decide which value to use? – Chris Doyle Dec 21 '20 at 10:15
  • Each key can appear only once – You Idjit Dec 21 '20 at 14:38

2 Answers2

2

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);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
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);

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;
}
ikegami
  • 367,544
  • 15
  • 269
  • 518