in reply to Compare Two Hash refs of Hashes

Union and Intersection operate on sets. If you want to operate on hashes you first have to define what you mean by that. Is it the intersection of the keys, the values or both? What would be the union of 'seqnum'=>43 and 'seqnum'=>44 (as you can't store two values with the same key) ?

Replies are listed 'Best First'.
Re^2: Compare Two Hash refs of Hashes
by kalyanrajsista (Scribe) on Jul 15, 2010 at 09:54 UTC

    Here is my requirement and basically want to update the Database

    I want all the keys and values from the hash refs.

    Compare $old and $new and

    ~ get any new keys which should be INSERTED into DB

    ~ get common keys, but again check for any changes in their values. If so UPDATE DB

    ~ get the missing keys in $new with that of $old. If so, DELETE from DB

      # Throw away all keys in old hash that are in new, update keys that ch +anged or are new foreach $key (keys %$new) { if (exists($old->{$key}) { if ($old->{$key} ne $new->{$key}) { updateindatabase($key,$new->{$key}); } delete $old->{$key}; } else { updateindatabase($key,$new->{$key}); } # remove keys that are only in old foreach $key (keys %$old) { deleteindatabase($key); }

      That should do it. I assume the hash is very big, otherwise simply deleting and just storing the new hash would be faster and simpler

        Thanks for your efforts

        I want to check only particular fields like sdrpretax_vcd taxamt_vcd sdrposttax_vcd dchdetaildate in $old and $new hashes. If there are any differences, I must update the values from $new hash. Please let me know if I can achieve in minimal steps rather than looping around the hashes...

        foreach my $TAP ( keys %{$new} ) { ; if ( exists($old->{$TAP}) ) { ; my $hasUpdated = '0'; foreach my $check_field ( qw(sdrpretax_vcd taxamt_vcd sdrpostt +ax_vcd dchdetaildate) ) { ; if ( $new->{$TAP}->{$check_field} ne $old->{$TAP}->{$check +_field} ) { ; $hasUpdated = 1; last; } } if ( $hasUpdated ) { print " Has to update the DB now "; } } }
      what about this straight forward approach?

      while ( ($ko,$vo) = each %$old ) { while ( ($kn,$vn) = each %$new ) { # compare } }

      of course there are other tricks possible like using hash slices or array slices of keys of hashes and so on...

      Cheers Rolf