Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Comparing two hashes

by midnight (Initiate)
on Apr 01, 2010 at 20:34 UTC ( [id://832380]=perlquestion: print w/replies, xml ) Need Help??

midnight has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am a beginner at perl and I am trying to compare elements of two hashes. I have no idea how to do this. Can anyone help. Thanks

Replies are listed 'Best First'.
Re: Comparing two hashes
by kennethk (Abbot) on Apr 01, 2010 at 20:47 UTC
Re: Comparing two hashes
by moritz (Cardinal) on Apr 01, 2010 at 20:46 UTC
    What exactly do you want to compare? the values for given keys? or if the set of keys in one hash is the same as in the other? or something else?
Re: Comparing two hashes
by toolic (Bishop) on Apr 01, 2010 at 21:36 UTC
Re: Comparing two hashes
by dwm042 (Priest) on Apr 01, 2010 at 21:08 UTC
    As other monks have pointed out, the question is a little vague. If what you're trying to do is compare elements in one hash with elements in another hash, and the key values do not matter, you could use code something like this:
    #!/usr/bin/perl use warnings; use strict; my %giant = ( fee => 'fi', fo => 'fum', I => 'smell' ); my %mouse = ( eeeny => 'meeny', miny => 'mo', nose => 'smell' ); my $out = "giant\{%s\} equals mouse\{%s\}\n"; for my $g ( sort keys %giant ) { for my $m ( sort keys %mouse ) { printf $out, $g, $m if ( $giant{$g} eq $mouse{$m} ); } }
        Actually, that's what I intended to do, ruzam. And that's what I said I was going to do. One example, of one possible interpretation of the OP's question, was all I wanted to provide.
Re: Comparing two hashes
by bichonfrise74 (Vicar) on Apr 01, 2010 at 20:45 UTC
    Something like...

    1. Create an outer for loop on 1st hash.
    2. Create an inner for loop on the 2nd hash.
    3. If keys and values of 2nd hash element is equal to the 1st hash element, then they are the same.
      Doing a linear scan over an associative array is like trying to club someone to death with a loaded Uzi -- TimToady

      Sounds like you don't need step 2. at all, since you can simply access the hash item by key.

      Perl 6 - links to (nearly) everything that is Perl 6.
Re: Comparing two hashes
by vennila (Novice) on Apr 02, 2010 at 06:37 UTC
    Try to check test::Deep or Storable module.
Re: Comparing two hashes
by midnight (Initiate) on Apr 14, 2010 at 22:28 UTC
    Thank you guys. This has helped

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://832380]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-25 10:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found