2011-10-04 36 views
4

所有使用的密钥应该出现在初始%哈希定义中。如果散列键在初始散列定义中没有定义,是否有办法让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. 

有没有办法做到这一点?

+0

有一种叫做类的东西。你可能需要这个。 –

+0

您可以批准答案的时间。 – DavidO

回答

5

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

+1

所以它听起来像标准Hash :: Util :: lock_keys函数一样。 –

+0

+1 @davorg:我很确定Core中有些东西,但我的搜索功能很弱。 – toolic

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

如果你确实需要在编译时使用它,把它放在'BEGIN'块中。 – tripleee

+2

-1:这要求您在每次使用散列时手动测试每个散列键的存在性,这与问题希望使用不存在的键自动失败的愿望是相反的。 –

8

模块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. 
相关问题