Reputation: 1099
I'm trying to use the code from make perl shout when trying to access undefined hash key, but it doesn't work.
I assume something has changed in the way tie
works in the past 10 years.
The error I get is:
Safe::Hash must define either a TIEHASH() or a new() method at /home/bennett/work/stock/Indicator.pm line 97.
I only need this for about 5% of the hashes I use, and I'm hoping to use something that doesn't change the interface (i.e. $foo{bar}
). That is, I'd prefer not to use Moose
or something involving accessor methods.
Here's why: I want to turn it on for debugging and development, and turn it off, otherwise. The program and computer are slow enough as it is.
Any fixed up code (see the link above), or other solutions are welcome.
This is Perl 5, version 16, Subversion 3 (v5.16.3) built for x86_64-Linux-thread-multi
Upvotes: 1
Views: 325
Reputation: 9231
For a nonexistent hash key, which is different from a hash key that exists but has an undefined value, you can use lock_hash from Hash::Util. Note that it also restricts any values from changing. Unfortunately lock_keys, which otherwise is closer to what you ask for, does not cause an error on accessing a nonexistent key unless you try to set it.
use strict;
use warnings;
use Hash::Util 'lock_hash';
my %foo = (a => 1, b => 2);
lock_hash %foo;
print $foo{c}; # error
This is the same underlying mechanism used by Const::Fast for read-only hashes, but it is a bit confusing as it tries to act both as read-only (existing values can't be changed) and restricted (nonexistent keys can't be accessed).
Upvotes: 3