简体   繁体   English

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

[英]How to do `defined` with a hash slice

I'm trying to learn Perl better, and learn hash slices.我正在尝试更好地学习 Perl,并学习 hash 切片。

Instead of 3 different if (defined statements, I'm trying to tidy the code to make it more maintainable and readable, but have come across the following conundrum:我试图整理代码以使其更易于维护和阅读,而不是 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
}

I've read How to do sum of hash reference slice?我读过如何计算 hash 参考切片的总和? and https://perlmonks.org/?node=References+quick+reference to no avail.https://perlmonks.org/?node=References+quick+reference无济于事。

This person Jane is missing both age and BMI information, so the if (defined statement should say that some terms are missing, but is instead passing.这个人Jane缺少ageBMI信息,因此if (defined的语句应该说缺少某些术语,但它是通过的。

I get the same error whether I use @{ $hashref->{Jane} }{@needed_terms} or %{ $hashref->{Jane} }{@needed_terms}无论我使用@{ $hashref->{Jane} }{@needed_terms}还是%{ $hashref->{Jane} }{@needed_terms}我都会得到同样的错误

I've also thought that maybe defined is returning how many terms of the slice are defined, but that isn't true.我还认为 maybe defined返回的是切片中定义了多少项,但事实并非如此。

How can I set if (defined statement on a hash slice properly?如何正确设置if (defined statement on a hash slice?

This is a good place to use all from List::Util :这是使用List::Utilall内容的好地方:

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
}

It loops through all the needed terms and checks to see if each exists as key to the Jane hash.它遍历所有需要的术语并检查是否每个都作为Jane hash 的键存在


One of my favorite docs for Perl Data Structures is perldoc perldsc .我最喜欢的 Perl 数据结构文档之一是perldoc perldsc It is more of a step-by-step tutorial than References quick reference .它比References quick reference更像是一个循序渐进的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM