Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Comparing all keys in a hash

by gmax (Abbot)
on Mar 20, 2003 at 12:03 UTC ( [id://244573]=note: print w/replies, xml ) Need Help??


in reply to Comparing all keys in a hash

Actually, the way you are doing it, you are comparing arrays. Therefore you may find useful this node:

comparing arrays

The best method there was MeowChow's at (MeowChow) Re2: (Efficiently) comparing arrays

To take advantage of hashes capabilities, though, I would rather use something like

#!/usr/bin/perl -w use strict; my %first = ( aa => 1, bb => 2, cc => 3, ee => 6); my %second = ( bb=> 2, cc => 3, dd => 4 ); sub compare_one_hash_keys { my ($h1, $h2) = @_; return grep ( {not exists $h2->{$_} } keys %$h1) } sub compare_both_hash_keys { my ($h1, $h2) = @_; return grep ( {not exists $h2->{$_} } keys %$h1), grep ( {not exists $h1->{$_} } keys %$h2) ; } print compare_one_hash_keys( \%first, \%second), "\n"; print compare_one_hash_keys( \%second, \%first), "\n"; print compare_both_hash_keys( \%first, \%second), "\n"; __END__ prints: aaee dd aaeedd

The first sub returns an array of keys present in one hash and missing in the other one. The second one combines the differences in both hashes. I think you may use this method to implement what is closer to your needs.

 _  _ _  _  
(_|| | |(_|><
 _|   

Log In?
Username:
Password:

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

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

    No recent polls found