如何使用哈希切片进行“定义”

How to do `defined` with a hash slice

我正在尝试更好地学习 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
}

我读了 and 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。它比 参考快速参考.

更像是一个循序渐进的教程