是否有一个模块或最佳方法来比较基于键的2个哈希值以及第一个和第二个哈希值中缺少的检索和打印值?
我有两个描述特定配置的哈希值 我想比较配置的两个历史状态。特别是我有兴趣知道哪个密钥已被删除以及哪个密钥已被添加。无需知道密钥的编辑位置(即,这不会发生)。
示例:
Hash 1 keys:
aaa
bbb
ccc
ddd
Hash 2 keys:
aaa
xxx
bbb
ccc
yyy
结果应该是这样的:
xxx added
ddd deleted
yyy added
有什么想法吗?
答案 0 :(得分:2)
您可以使用List::Compare执行此任务:
use strict;
use warnings;
use List::Compare;
my %hash1 = map { $_ => undef } qw/aaa bbb ccc ddd/;
my %hash2 = map { $_ => undef } qw/aaa xxx bbb ccc yyy/;
my $lc = List::Compare->new( [ keys %hash1 ], [ keys %hash2 ] );
my @hash1Only = $lc->get_Lonly;
my @hash2Only = $lc->get_Ronly;
print "Added: @hash2Only\nDeleted: @hash1Only\n";
输出:
Added: xxx yyy
Deleted: ddd
希望这有帮助!
答案 1 :(得分:2)
sub compare {
my ($a, $b) = @_;
[grep !exists $b->{$_}, keys %$a], [grep !exists $a->{$_}, keys %$b];
}
my @keys1 = qw(aaa bbb ccc ddd);
my @keys2 = qw(aaa xxx bbb ccc yyy);
my (%hash1, %hash2);
@hash1{@keys1}=();
@hash2{@keys2}=();
my ($deleted, $added) = compare(\%hash1, \%hash2);
print "Added: @$added, Deleted: @$deleted\n";
答案 2 :(得分:0)
遍历所有keys
哈希值1.对于每个检查,哈希值为exists
。如果不是,则删除它。如果是,delete
密钥形式哈希2.完成后,哈希2中的所有剩余keys
都是已添加的。{/ p>
编辑:我假设您知道如何在Perl中编写代码并且只需要一个想法。如果答案听起来很奇怪,请查看Perldoc中写的like this
字样。
答案 3 :(得分:0)
use warnings;
use strict;
my @array1 = qw (aaa bbb ccc ddd);
my @array2 = qw(aaa xxx bbb ccc yyy);
my (%hash1, %hash2);
@hash1{@array1} = 1;
@hash2{@array2} = 1;
foreach (keys %hash2){
print "added $_\n" unless exists $hash1{$_};
}
foreach (keys %hash1){
print "removed $_\n" unless exists $hash2{$_};
}
打印:
added xxx
added yyy
removed ddd