Question

this is my case:

%h1 = {
    'a' => 1,
    'b' => 3,
    'c' => 10,
    'x' => 12
}

%h2 = {
    'd' => 3,
    'f' => 5,
    'a' => 10,
    'x' => 0,5
}

I'd like to have this output :

h1, a, 1 | h2, a, 10
h1, c, 10 | h2, c, -
h1, f, - | h2, f, 5

and so on... with my code I can compare two hashes if the keys are the same, but I can't do anything else

foreach my $k(keys(%bg)) {
    foreach my $k2 (keys(%sys)) {
        if ($k eq $k2){
            print OUT "$k BG :  $bg{$k} SYS: $sys{$k2}\n";
        }
    }
}
Was it helpful?

Solution

It sounds like you just want to iterate over the unique keys between two hashes:

use strict;
use warnings;

use List::MoreUtils qw(uniq);

my %h1 = ('a' => 1, 'b' => 3, 'c' => 10, 'x' => 12);
my %h2 = ('a' => 10, 'd' => 3, 'f' => 5, 'x' => 0);

for my $k (sort +uniq (keys %h1, keys %h2)) {
    printf "%s h1: %-2s h2: %-2s\n", map {$_//'-'} ($k, $h1{$k}, $h2{$k});
}

Outputs:

a h1: 1  h2: 10
b h1: 3  h2: -
c h1: 10 h2: -
d h1: -  h2: 3
f h1: -  h2: 5
x h1: 12 h2: 0

OTHER TIPS

#!/usr/bin/env perl

use strict;
use warnings;

use Text::Table;

my %h1 = ('a' => 1, 'b' => 3, 'c' => 10, 'x' => 12);
my %h2 = ('a' => 10, 'd' => 3, 'f' => 5, 'x' => 0);

my $table = Text::Table->new(
    'Key',    \' | ',
    'Hash 1', \' | ',
    'Hash2'
);

$table->load(
    map [$_, $h1{$_}, $h2{$_}],
    sort keys %{{ map {$_ => 1} keys %h1, keys %h2}}
);

print $table;

Output:

Key | Hash 1 | Hash2
a   |  1     | 10
b   |  3     |
c   | 10     |
d   |        |  3
f   |        |  5
x   | 12     |  0

I think you need a full join on the hashes.Loop through first hash and get the corresponding values from the second hash and do the same with the second hash.

my %h1 = (
'a' => 1,
'b' => 3,
'c' => 10,
'x' => 12
);

my %h2 = (
'd' => 3,
'f' => 5,
'a' => 10,
'x' => 0
);

my %res;

foreach my  $k (keys %h1){
 $res{$k}="h1" . "," . "$k"   . "," . ($h1{$k} eq "" ? "-" : $h1{$k}) . "|" . "h2" . "," . "$k" . "," . ($h2{$k} eq "" ? "-" : $h2{$k});
}


foreach my  $k (keys %h2){
 $res{$k}="h1" . "," . "$k"   . "," . ($h1{$k} eq "" ? "-" : $h1{$k}) . "|" . "h2" . "," . "$k" . "," . ($h2{$k} eq "" ? "-" : $h2{$k});
}


foreach my $k (sort keys %res){
print $res{$k} . "\n"; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top