问题描述
我正在努力更好地学习 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? 无济于事。
此人 Jane
缺少 age
和 BMI
信息,因此 if (defined
语句应该说明缺少某些术语,而是通过了。
无论我使用 @{ $hashref->{Jane} }{@needed_terms}
还是 %{ $hashref->{Jane} }{@needed_terms}
都会出现相同的错误
我还认为 defined
可能会返回定义了切片的多少项,但事实并非如此。
如何在散列切片上正确设置 if (defined
语句?
解决方法
这是使用 List::Util 中的 all
的好地方:
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。它更像是一个分步教程,而不是参考快速参考。