Maybe I'm way off base, but it seems to me that a hash that only allows members of a known-at-compile-time list of keys is just an array with named indices, and would be better treated as such. This is much in line with kennethk's suggestion, except for the slight speed boost of using an array in the place of a hash. On the other hand, kennethk's solution allows a nice mix of compile-time checking and run-time flexibility:
use constant { COMPILE_KEY => 'compile_key' };
use strict;
my %hash = (
COMPILE_KEY() => 'yay',
runtime_key => 'still OK'
);
$hash{COMPLIE_KEY()}; # sadness
Finally, if you don't care about speed, then Tie::StrictHash is designed to do exactly what you want, via (obviously) tieing.
UPDATE: Of course, now that I think about it, Tie::StrictHash obviously can't do any compile-time checking, so you're probably better with the non-tie-based Hash::Util that moritz recommended. |