Perl中两个哈希的比较

时间:2011-06-10 18:45:48

标签: perl comparison hash

我遇到过这种情况。 在hash1中,第一列是键,其余是datavalue,类似于hash2。

所以我想做的就是比较这两个哈希和

如果记录在hash2中而不在hash1中,那么它是一个add

如果记录在hash1中而不在hash2中,那么它就是drop。

我想要添加和删除列表。我想与hash1和hash2进行比较,反之亦然,无需使用CPAN模块即可获得添加和删除。

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

在这种情况下,输出应该是这样的:

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

1 个答案:

答案 0 :(得分:2)

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

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

根据自己的喜好调整输出。