Search code examples
perlhash-of-hashesarrayofarrays

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= {
  '567' => 'A1',
  '689' => 'A2',
}

There will be no missing elements in either structure and there will no 'undef' values either.


Solution

  • 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);