I think the title is self-explanatory. Many times I have small typos and I get unexpected results when trying to access undefined hash keys. I know I can add some defined
check before each time I access a hash key, but I wonder if there's any cleaner way to warn against such cases....
Best, Dave
You can write a simple function for this:
Use Hash::Util:
output:
There are other functions that allow specifying which keys to allow, not just defaulting to what's already there.
This is probably best done with a tied hash. Tied variables allow you to define the implementation of the low level operations of the variable. In this case, we want a special fetch method that dies when accessing non-existant keys:
In the implementation of
Safe::Hash
above, I first loadTie::Hash
which providesTie::StdHash
. Setting@ISA
toTie::StdHash
provides our new package with tie methods that behave the same way as normal hashes. Each of the tie methods are outlined on http://perldoc.perl.org/perltie.htmlIn this case the only method to override is
FETCH
which is passed a reference to the hidden tied object (a hashref in this case), and the key to use. It checks if the slot exists, and either returns it or throws an error