Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: diff of two hashes.

by johannz (Hermit)
on May 12, 2000 at 21:10 UTC ( #11323=note: print w/replies, xml ) Need Help??

in reply to diff of two hashes.

My couple of cents worth.

Two major parts to the compareHashes subroutine.

  1. Build a Hash of all keys, with a count of how many hashes that key appears in
  2. Go though list of keys, display whether in one hash, or if different between the two hashes.
#! /usr/bin/perl my $skipOdds = 1000; my $randomOdds = 1000; my $rHash1 = createHash(57000); my $rHash2 = createHash(57000); compareHashes($rHash1, $rHash2); exit; sub createHash { my $size = shift || 100; my $rHashRef = shift || {}; my $key = ''; my $value = ''; for( my $current = 0; $current < $size; $current++ ) { # If rand number comes up 0, skip. next unless int(rand($skipOdds)); $value = $key = sprintf('%X', $current); unless (int(rand($randomOdds))) { $value = sprintf('%X', int(rand($size))); }; $rHashRef->{$key} = $value; } return $rHashRef; #Allows use as RV for assignment; } sub compareHashes { my $rHash1 = shift || {}; my $rHash2 = shift || {}; my %keys; my $currentKey; map {$keys{$_}++} keys(%$rHash1); map {$keys{$_}++} keys(%$rHash2); foreach $currentKey (sort(keys(%keys))) { if ($keys{$currentKey} == 2) { # In both hashes, let's see if it's the same. if ($rHash1->{$currentKey} ne $rHash2->{$currentKey}) { print "Key $currentKey is different\n"; } } else { # Only in one hash, let's see which one. if (exists($rHash1->{$currentKey})) { print "Key $currentKey only in Hash1\n"; } else { print "Key $currentKey only in Hash2\n"; } } } }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11323]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2019-07-24 02:09 GMT
Find Nodes?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?

    Results (32 votes). Check out past polls.