Sunny
Sunny

Reputation: 175

Comparison of two hashes in Perl

I have come across this situation. In the hash1 first column is the key and the rest is datavalue, similarly in the hash2.

So what I m trying to do is I want to compare these two hashes and

if a record is in hash2 and not in hash1 then its an add

if a record is in hash1 and not in hash2 then its a drop.

I want both adds and drops list.I want to compare with hash1 with hash2 or vice-versa and get the adds and drops without using CPAN modules.

Hash1

739574562   Dexheimer       James           University Libraries            Coord Fast Cataloging   jdexheim
766631088   Rolls           Erlinda         University Libraries            Prof-Support-Waldo Lib  rolls
204707142   Reish           Joseph          University Libraries            Dean University
127759797   PRIEST          DANIEL          University Libraries            Temporary Student-Non e 
133708988   BRODHEAD        MATTHEW         University Libraries            Temporary Student-Non e 
......
......
......

Hash2

381753669   BRAMAN                  MELISSA             University Libraries            Temporary Non-Exempt    
127759797   PRIEST                  DANIEL              University Libraries            Temporary Student-Non e 
133708988   BRODHEAD                MATTHEW             University Libraries            Temporary Student-Non e 
204707142   Reish                   Joseph              University Libraries            Dean University
......
......
......

In this case output should be like this:

Adds  : BRAMAN          MELISSA         University Libraries            Temporary Non-Exempt 

Drops : Dexheimer       James           University Libraries            Coord Fast Cataloging   jdexheim
        Rolls           Erlinda         University Libraries            Prof-Support-Waldo Lib  rolls

Upvotes: 1

Views: 288

Answers (1)

ikegami
ikegami

Reputation: 386696

for (keys(%h1)) {
   if (!exists($h2{$_})) {
      print("Dropped $_\n");
   }
}

for (keys(%h2)) {
   if (!exists($h1{$_})) {
      print("Added $_\n");
   }
}

Tweak the output to your liking.

Upvotes: 2

Related Questions