所有使用的密钥都应该出现在初始的%哈希定义中。
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.
有办法做到这一点吗?
答案 0 :(得分:8)
自5.8.0以来,模块Hash::Util已成为Perl的一部分。这包括一个'lock_keys'函数,它可以实现你想要的东西。如果您尝试向哈希添加密钥,则会产生运行时(非编译时)错误。
#!/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.
答案 1 :(得分:5)
Tie::StrictHash会死,但它会在运行时而不是编译时执行。
答案 2 :(得分:-4)
use strict;
my %hash = ('key1' => 'abcd', 'key2' => 'efgh');
my $ke = 'key3';
if (!exists $hash{$ke}) {
exit;
}