PERL,比较2个哈希,列出所有键和所有值,即使它们不同

时间:2014-04-18 11:50:47

标签: perl hash comparison associative-array

这是我的情况:

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

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

我想要这个输出:

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

依旧...... 用我的代码我可以比较两个哈希,如果键是相同的, 但我不能做任何其他事情

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

3 个答案:

答案 0 :(得分:1)

听起来你只想迭代两个哈希之间的唯一键:

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

输出:

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

答案 1 :(得分:1)

#!/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;

输出:

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

答案 2 :(得分:0)

我认为你需要对哈希进行完全连接。通过第一个哈希并从第二个哈希中获取相应的值并对第二个哈希执行相同的操作。

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