Re: Common hash keysby radiantmatrix (Parson)
|on Jun 09, 2008 at 20:46 UTC||Need Help??|
OK, let's walk through this.
A hash reference is just a reference to a hash, getting at the hash is a simple matter -- so we can ignore the "reference" part of your question for now, and focus on how to determine if two hashes share any keys. Let's start with two simple hashes:
We know the keys they have in common are two and three, but how to find that out in code?
First, let's rephrase the question a little bit: if I know all the keys in one hash, how do I find out if any of those keys exist in another hash?
Let's work backwards from that. How do we find out if the %a hash contains a key -- let's say, the key one? That would be exists:
Ok, so how do we find out what keys a hash has? How about keys:
So, if we get the list of keys for hash %a, all we have to do is loop through them and see if %b has any that match. Here's the long way:
Make sense? Of course, this type of activity -- looking through a list to find items that meet a criterion -- is so common that Perl has a function for it: grep. So here's a short version:
Now let's add "references" back to the mix. Let's make references to our hashes:
Now, we do as above, but dereferencing as appropriate: