如果在初始哈希定义中未定义哈希键,有没有办法使perl编译失败?



使用的所有键都应该出现在初始%散列定义中。

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.

有办法做到这一点吗?

模块Hash::Util自5.8.0以来一直是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.

Tie::StrictHash在您尝试分配新的散列键时死亡,但它在运行时而不是编译时执行。

use strict; 
my %hash = ('key1' => 'abcd', 'key2' => 'efgh'); 
my $ke = 'key3';
if (!exists $hash{$ke}) {
exit;
}

相关内容