All keys used should be present in the initial %hash definition.
use strict;
my %hash = ('key1' => 'abcd', 'key2' => 'efgh');
$hash{'key3'} = '1234'; ## <== I'd like for these to fail at compilation.
$hash{'key4'}; ## <== I'd like for these to fail at compilation.
Is there a way to do this?
The module Hash::Util has been part of Perl since 5.8.0. And that includes a 'lock_keys' function that goes some way to implementing what you want. It gives a runtime (not compile-time) error if you try to add a key to a hash.
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Hash::Util 'lock_keys';
my %hash = (key1 => 'abcd', key2 => 'efgh');
lock_keys(%hash);
$hash{key3} = '1234'; ## <== I'd like for these to fail at compilation.
say $hash{key4}; ## <== I'd like for these to fail at compilation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With