弄清变量何时为假,并依此做出正确的判断

基本判断如下:0,‘0’,undef, ‘’(空字符串)都是假值。其他皆为真。

1.数组的尾部

判断是否遍历了整个数组,不能用数组的值判断,可以用foreach函数来遍历数组的元素,并跳过未定义的值:

foreach my $cat (@cats) (
  next unless defined $cat;
  print "I have a cat names $ca\n";
)

不要把undef当成数组的最后一个元素,应该使用$#cats的写法获得数组的最后一个元素的下标。

2.散列值

假设%hash未定义,是个空散列。那么下边的几种方式测试都是假

my %hash;
if ( $hash{'foo'} )           #
if (defined $hash{'foo'})     #
if (exists $hash('foo'))      #

一旦给某个键值赋了值,这个键也就存在了,哪个这个值代表的是假

$hash('foo')=undef;
if($hash{'foo'})             #
if(defined $hash{'foo'})     #
if(exists $hash{'foo'})      #

如果某个键的值明确,哪怕是个代表假的值,这个键对应的值也已经定义了。

$hash('foo')=‘’;
if($hash{'foo'})             #
if(defined $hash{'foo'})     #
if(exists $hash{'foo'})      #
原文地址:https://www.cnblogs.com/tjxwg/p/2916238.html