首页 > 解决方案 > 给定许多变量来测试定义性,如何(轻松)找出未定义的变量?

问题描述

今天看到这段代码:

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……?仍然需要通过所有这些,手动测试每一个?

难道没有更短、更“神奇”的方式来告诉哪个变量未定义?

标签: perl

解决方案


您可以创建一个表来简化一点:

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";
    }
}

推荐阅读