If I understand correctly, calling if (exists $ref->{A}->{B}->{$key}) { ... }
will spring into existence $ref->{A}
and $ref->{A}->{B}
even if they did not exist prior to the if
!
This seems highly unwanted. So how should I check if a "deep" hash key exists?
Take a look at Data::Diver. E.g.:
Pretty ugly, but if $ref is a complicated expression that you don't want to use in repeated exists tests:
You could use the autovivification pragma to deactivate the automatic creation of references:
It's also lexical, meaning it'll only deactivate it inside the scope you specify it in.
Check every level for
exist
ence before looking at the top level.If you find that annoying you could always look on CPAN. For instance, there is
Hash::NoVivify
.It's much better to use something like the autovivification module to turn off that feature, or to use Data::Diver. However, this is one of the simple tasks that I'd expect a programmer to know how to do on his own. Even if you don't use this technique here, you should know it for other problems. This is essentially what
Data::Diver
is doing once you strip away its interface.This is easy once you get the trick of walking a data structure (if you don't want to use a module that does it for you). In my example, I create a
check_hash
subroutine that takes a hash reference and an array reference of keys to check. It checks one level at a time. If the key is not there, it returns nothing. If the key is there, it prunes the hash to just that part of the path and tries again with the next key. The trick is that$hash
is always the next part of the tree to check. I put theexists
in aneval
in case the next level isn't a hash reference. The trick is not to fail if the hash value at the end of the path is some sort of false value. Here's the important part of the task:Don't be scared by all the code in the next bit. The important part is just the
check_hash
subroutine. Everything else is testing and demonstration:Here's the output (minus the data dump):
Now, you might want to have some other check instead of
exists
. Maybe you want to check that the value at the chosen path is true, or a string, or another hash reference, or whatever. That's just a matter of supplying the right check once you have verified that the path exists. In this example, I pass a subroutine reference that will check the value I left off with. I can check for anything I like:And its output: