Reputation: 1218
Say I have 2 hashes:
my %hash1 = ('file1' => 123, 'file3' => 400);
my %hash2 = ('file1' => 123, 'file2' => 300, 'file3' => 400);
What's the best way to determine if the key/value pairs in hash1 do not exist in hash2?
Upvotes: 0
Views: 187
Reputation: 29854
I like to use the new pairwise features of List::Util
. (Well, actually I've been using my own version of them for a long time, even before 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
;
Note that $hash1{file3}
was changed to 402, to make a solution set.
Upvotes: 1
Reputation: 6578
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};
}
Which outputs nothing, as all the keys that exist in %hash1
also exist in %hash2
, and all the values for each key are the same
Upvotes: 3