这是我的情况:
%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";
}
}
}
听起来您只想迭代两个哈希之间的唯一键:
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
#!/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;
输出:
钥匙|哈希 1 |哈希2 一个 | 1 | 10 乙| 3 | c | 10 | 10 d | | 3 f | | 5 x| 12 | 12 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";
}