加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:21:59 所属栏目:大数据 来源:网络整理
导读:使用的所有密钥都应存在于初始%哈希定义中. 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. 有没
使用的所有密钥都应存在于初始%哈希定义中.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读