Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re^2: Compare Two Hash refs of Hashes

by kalyanrajsista (Scribe)
on Jul 15, 2010 at 09:54 UTC ( #849733=note: print w/replies, xml ) Need Help??

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

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

Replies are listed 'Best First'.
Re^3: Compare Two Hash refs of Hashes
by jethro (Monsignor) on Jul 15, 2010 at 13:11 UTC
    # 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 "; } } }
        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; }
Re^3: Compare Two Hash refs of Hashes
by LanX (Chancellor) on Jul 15, 2010 at 10:29 UTC
    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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://849733]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2017-05-22 22:38 GMT
Find Nodes?
    Voting Booth?