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

前端之家收集整理的这篇文章主要介绍了如果在初始哈希定义中没有定义哈希键,有没有办法使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.

有没有办法做到这一点?

解决方法

自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.

猜你在找的Perl相关文章