Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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 } }

Log In?
Username:
Password:

What's my password?
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 chanting in the Monastery: (4)
As of 2019-07-20 18:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?