One option is iterate through both hashes in-sync (much like the "merge" step in a mergesort) and spit out any differences. What I present below is meant as more of an algorithm than an actual implementation (though it does work). It could be tweaked quite a bit in actual implementation to get much better performance. This is probably not the best perl implementation, but it is a good general-purpose algorithm for doing "diffrence of lists/difference of hashes".
my @k1=sort keys %h1; my @k2=sort keys %h2; my $k1; my $k2; while((scalar @k1 > 0)&&(scalar @k2 > 0)){ if(!defined $k1){ $k1=shift @k1; } if(!defined $k2){ $k2=shift @k2; } if($k1 eq $k2){ if($h1{$k1} ne $h2{$k2}){ # .. keys match but contents dont } undef $k1; undef $k2; }elsif($k1 lt $k2){ # .. key in k1 and not in k2 undef $k1; }else{ # .. key in k2 and not in k1 undef $k2; } } if(defined $k1){ foreach ($k1,@k1){ # .. key in k1 and not in k2 } } if(defined $k2){ foreach ($k2,@k2){ # .. key in k2 and not in k1 } }
In reply to RE: diff of two hashes.
by lhoward
in thread diff of two hashes.
by ChuckularOne
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |