gpt4 book ai didi

perl - 如何用哈希切片做 `defined`

转载 作者:行者123 更新时间:2023-12-03 23:40:51 24 4
gpt4 key购买 nike

我正在尝试更好地学习 Perl,并学习哈希切片。
而不是 3 个不同的 if (defined语句,我正在尝试整理代码以使其更具可维护性和可读性,但遇到了以下难题:

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use feature 'say';
use autodie ':all';
use Carp 'confess';
use DDP; # a.k.a. Data::Printer
use JSON 'decode_json';

my $hashref;
$hashref->{Jane} = decode_json('{"sex":"Female","Mortality_Status":"Alive", "latest_date":"2020-11-26","Hospitalized":"no","Risk_Status":"NA"}');
p $hashref; # pretty print the data
my @needed_terms = qw(age BMI sex);
if (defined @{ $hashref->{Jane} }{@needed_terms}) {
say 'all terms are defined.'; # this is what it says, which is WRONG!!!
} else {
say 'some terms are missing.'; # Jane is missing BMI and age, so the script should print here
}
我已阅读 How to do sum of hash reference slice?https://perlmonks.org/?node=References+quick+reference无济于事。
此人 Jane两者都缺少 ageBMI信息,所以 if (defined声明应该说缺少某些术语,而是通过了。
无论我使用 @{ $hashref->{Jane} }{@needed_terms},我都会遇到同样的错误或 %{ $hashref->{Jane} }{@needed_terms}我也想过,也许 defined返回定义了切片的多少项,但事实并非如此。
如何设置 if (defined对哈希切片的语句正确吗?

最佳答案

这是使用的好地方all来自 List::Util :

use List::Util qw(all);

if (all { exists $hashref->{Jane}{$_} } @needed_terms) {
say 'all terms are defined.';
} else {
say 'some terms are missing.'; # Jane is missing BMI and age, so the script should print here
}
它遍历所有需要的术语并检查是否每个 exists作为 Jane 的关键哈希。

我最喜欢的 Perl 数据结构文档之一是 perldoc perldsc .它更像是一个循序渐进的教程,而不是引用快速引用。

关于perl - 如何用哈希切片做 `defined`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65957545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com