ETOOBUSY 🚀 minimal blogging for the impatient
Hash::Util
TL;DR
Hash::Util can be useful.
Hash::Util is a Perl CORE module that can come handy when dealing with configuration hashes.
What I mean with configuration hash is that many times I collect configurations in a hash, e.g. when parsing a function’s options or when reading the command-line arguments for a program.
Hashes are very powerful and flexible, which is both a good thing (as they are easy to use) and a risky one. It’s risky because accessing a hash by key opens the way to undetected typos.
What I mean is that if I define a configuration variable like this:
my $config_foo = 42;
and later I try to use it, but I mistype the name:
if ($config_FOO < 10) { # ... nope, this variable does not exist!
the compiler will fail to comply and ask me to correct my error. On the other hand, with hashes:
$config{foo} = 42;
...
if ($config{FOO} < 10) { # no loud complains
will at most produce a runtime warning about comparing an undef value with an integer, which might go totally unnoticed.
It seems that the solution to this problem has been in CORE and right under my nose since the dawn of my Perl time, in the form of Hash::Util:
use Hash::Util qw< lock_keys >;
my %config;
$config{foo} = 42;
$config{bar} = 'whatever';
# ... populate with other key/value pairs as needed
lock_keys(%config);
From now on, %config
is locked, so…
if ($config{FOO} < 10) { # ... runtime complain
It’s something happening at runtime, but at least it does not go unnoticed!
Often times I collect options in a reference to a hash, but Hash::Util has me covered too:
use Hash::Util qw< lock_ref_keys >;
my $config = { foo => 42, ... };
lock_ref_keys($config);
If we also want to freeze the values, turning them into constants,
it’s possible to use lock_hash
and lock_hashref
.
It’s a bit strange that this has no direct counter part in CORE to set a single scalar value readonly.
Stay safe and locked!