in reply to Re^2: Compare Two Hash refs of Hashes
in thread Compare Two Hash refs of Hashes

# 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

Replies are listed 'Best First'.
Re^4: Compare Two Hash refs of Hashes
by kalyanrajsista (Scribe) on Jul 16, 2010 at 16:57 UTC

    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 "; } } }
      Why are your requirements changing all the time? Maybe you want this:
      if ( exists $new->{$TAP}->{$check_field} and (not exists $old->{$TAP}->{$check_field} or $new->{$TAP}->{$che +ck_field} ne $old->{$TAP}->{$check_field}) ) { $hasUpdated = 1; last; }