perl - 给定许多变量来测试定义性,如何(轻松)找出未定义的变量?
问题描述
今天看到这段代码:
if ( not defined($reply_address)
or not defined($from_name)
or not defined($subject)
or not defined($date) )
{
die "couldn’t glean the required information!";
}
(Jeffrey Friedl,“掌握正则表达式”,第 59 页,第 3 版。)
我想“我怎么知道哪个变量失火了?”
当然,如果只有 4 个变量要测试,如上例所示,可以得出:
if ( not defined $reply_address )
{
die "\$reply_address is not defined"
}
elsif ( not defined $from_name )
{
die "\$from_name is not defined"
}
elsif ...
但是如果有 14 个变量呢?还是40……?仍然需要通过所有这些,手动测试每一个?
难道没有更短、更“神奇”的方式来告诉哪个变量未定义?
解决方案
您可以创建一个表来简化一点:
use strict;
use warnings;
my $reply_address = "xyz";
my $from_name;
my $subject = "test";
my $date;
my @checks = (
[\$reply_address, '$reply_adress'],
[\$from_name, '$from_name'],
[\$subject, '$subject'],
[\$date, '$date'],
);
for my $check (@checks) {
if (not defined ${$check->[0]}) {
die $check->[1] . " is not defined";
}
}
推荐阅读
- css - 溢出的内容显示在焦点上
- python - Python 安装问题:我复制了 python3-config 以移动到所需的路径,但无法访问它
- javascript - 我收到 BadTokenException 或 InvalidDisplayException,在 WebView 中打开微调器时进行清理
- java - 通过接口自动装配 Spring Bean
- python - 突然的 Tensorflow / Keras Google Colab 依赖问题 `AttributeError: module 'tensorflow._api.v1.compat.v2' has no attribute '__internal__'`
- sql - 我们可以在 BigQuery 中自定义函数吗?如何在 BigQuery 中创建日期参数?
- asp.net-core - .Net Core 3.1 web api应用响应迟了,怎么办?
- sql - SQL插入无意中添加了多行
- php - PHP - 带夏令时调整的 12 小时格式
- php - HTML 表格上的单个复选框