perlhash

Perl, comparing 2 hashes, list all keys and all values even if they are different


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";
        }
    }
}

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