0
說我有2個散列:確定是否在HASH2存在在Perl HASH1數據
my %hash1 = ('file1' => 123, 'file3' => 400);
my %hash2 = ('file1' => 123, 'file2' => 300, 'file3' => 400);
什麼,以確定是否在HASH2不存在HASH1鍵/值對的最佳方式?
說我有2個散列:確定是否在HASH2存在在Perl HASH1數據
my %hash1 = ('file1' => 123, 'file3' => 400);
my %hash2 = ('file1' => 123, 'file2' => 300, 'file3' => 400);
什麼,以確定是否在HASH2不存在HASH1鍵/值對的最佳方式?
my %hash1 = ('file1' => 123, 'file3' => 400);
my %hash2 = ('file1' => 123, 'file2' => 300, 'file3' => 400);
foreach my $key (keys %hash1){
print "$key\t$hash1{$key}\n" if !exists $hash2{$key};
print "$hash1{$key}\n" if $hash1{$key} != $hash2{$key};
}
這沒什麼輸出,因爲所有存在於%hash1
鍵也%hash2
存在,併爲每個鍵中的所有值都相同
我喜歡用List::Util
新的配對功能。 (嗯,其實我一直在用自己的人版本很長一段時間,甚至List::Pairwise
前。)
use strict;
use warnings;
no warnings 'experimental';
use List::Util qw<pairgrep pairmap>;
my %hash1 = ('file1' => 123, 'file3' => 402);
my %hash2 = ('file1' => 123, 'file2' => 300, 'file3' => 400);
my @comp
= pairmap { $a }
pairgrep { not (exists $hash2{ $a } and $hash2{ $a } ~~ $b) }
%hash1
;
注意$hash1{file3}
改爲402,做一個解決方案集。
只是爲了澄清,通過「鍵/值對」,你的意思是兩個密鑰*和*的值在兩個哈希中必須相同嗎? – ThisSuitIsBlackNot
是的,這是正確的 – kernelpanic
因此,在您的示例中,'%hash1'中的所有鍵/值對都存在於'%hash2'中 – fugu