perl中对空值的判断处理
2014-08-17 21:20:19 阿炯

Perl中变量的空值应该有两种情形:变量尚为定义声明或已经定义了但没有对其进行赋值。

Assuming the variable $date is undefined when "empty":
if (!defined($date)) {
 $date = 'N/A';
}

或者更简洁(新增的短路操作符:定义否//,当只有//左边的表达式为undef时,才使用右边的值。这与'||'操作符不同,与逻辑判断无直接关系):
$date //= 'N/A';

Or if it really is an empty string, i.e. $date = ''; (this will also work in the case where $date is undefined, but you don't want to use this if you only want to identify the case where it is undefined):

if ($date eq '') {
 $date = 'N/A';
}

或简写为 (note that this will also set $date to N/A if $date is '0' or '' due to Perl's weak typing--注意:如果$date为值为'0'或空时,出于perl 弱类型特点也会将其值设为'N/A'):

$date ||= 'N/A';

关于两者的区别示例如下:
use v5.12;
my $dat;
$dat ||= 'N/A';

my $day='';
$day //= 'N/A';

say $dat;
say $day;

-----结果输出:
N/A
<空>

-----
my $dat='';
$dat ||= 'N/A';

my $day;
$day //= 'N/A';

say $dat;
say $day;

-----结果输出:
N/A
N/A

如果变量没有定义或为空时,为其赋值。

if ($date eq '') {
  $date = 'N/A';
}
Or more concisely (note that this will also set $date to N/A if $date is '0' due to Perl's weak typing):
$date ||= 'N/A';

For an undefined of empty string, in Perl 5.10 you can use the "defined-or" (//) operator to do the short version: $var = "N/A" unless length($var // '');

In Perl before 5.10 where "defined-or" is not available, you will either have to spell out the defined check: $var = "N/A" unless defined $var && length($var);

$date = "N/A" if (!defined($date) || ($date eq ""))

下例会在发现未初始化变量后临时屏蔽系统警告

no warnings 'uninitialized';

$_ = "N/A" unless length($_) foreach ($name,$date,$size,etc...);

use warnings 'uninitialized'; # Always turn back on.

$date = "N/A" if (!defined($date) || ($date eq ""))

undef $scalar; #$scalar will be undefined
$scalar = undef; #$scalar will exist, but with no value


参考文章
对Perl中defined、undef、exist的理解

Perl 数组或哈希变量空值处理