Is there a way make perl compilation fail if a hash key wasn't defined in the initial hash definition?
All keys used should be present in the initial %hash definition.
use strict;
my %hash = ('key1' => 'abcd', 'key2' => 'efgh');
$ha开发者_运维问答sh{'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.
Tie::StrictHash dies when you try to assign a new hash key, but it does it at runtime instead of compile time.
use strict;
my %hash = ('key1' => 'abcd', 'key2' => 'efgh');
my $ke = 'key3';
if (!exists $hash{$ke}) {
exit;
}
精彩评论