XP is just a number PerlMonks

### RE: diff of two hashes.

by lhoward (Vicar)
 on May 12, 2000 at 20:28 UTC ( #11315=note: print w/replies, xml ) Need Help??

in reply to diff of two hashes.

Are you looking for different keys, keys/value pairs or both?

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
}
}

Create A New User
Node Status?
node history
Node Type: note [id://11315]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2020-08-11 16:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Which rocket would you take to Mars?

Results (62 votes). Check out past polls.

Notices?