Nun*_*cio 4 perl hash compiler-errors
使用的所有密钥都应存在于初始%哈希定义中.
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.
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
自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.
Run Code Online (Sandbox Code Playgroud)