Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: comparing two hashes

by chipmunk (Parson)
on Feb 24, 2002 at 06:24 UTC ( #147151=note: print w/ replies, xml ) Need Help??

in reply to comparing two hashes

What you're really trying to do is subtract one set from another set. Hashes are the right tool, but this can be done with slices instead of loops.

# find old values that are not in new values my %deletions; @deletions{@oldvalues} = (); delete @deletions{@newvalues}; my @deletions = keys %deletions; # find new values that are not in old values my %additions @additions{@newvalues} = (); delete @additions{@oldvalues}; my @additions = keys %additions;

Update: fixed hash names.

Comment on Re: comparing two hashes
Download Code
Re: Re: comparing two hashes
by rinceWind (Monsignor) on Feb 24, 2002 at 22:14 UTC

    chipmunk is right that hashes are the right tool to use here. However, there are some instances when hashes are not usable:

    • When you need to preserve the order of the data
    • If you have duplicate keys.

    I have had quite a lot of success with Algorithm::Diff. See also Re: Comparing Elements of Two Arrays.

Re: Re: comparing two hashes
by Cody Pendant (Prior) on Feb 24, 2002 at 23:16 UTC

    That looks very much smarter and I'm sure it works, but can you (or anyone) please explain it a little more?

    What is

    @deletions{@oldvalues} = ();
    doing? I didn't know you could create hashes that way!

    Also, what's "%tmp"? --

      Thats something called a hash slice.This is used to refer to (and/or operate on) multiple hash elements at the same time.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://147151]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2015-01-30 02:41 GMT
Find Nodes?
    Voting Booth?

    My top resolution in 2015 is:

    Results (247 votes), past polls