![]() |
|
Perl: the Markov chain saw | |
PerlMonks |
Re: Common hash keysby radiantmatrix (Parson) |
on Jun 09, 2008 at 20:46 UTC ( [id://691095]=note: print w/replies, xml ) | 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:
We pass the whole hash referenced by $x to keys; and we use the dereference operator -> to make sure that exists looks at the hash referenced by $y.
<–radiant.matrix–>
Ramblings and references “A positive attitude may not solve all your problems, but it will annoy enough people to make it worth the effort.” — Herm Albright I haven't found a problem yet that can't be solved by a well-placed trebuchet
In Section
Seekers of Perl Wisdom
|
|