Perl-关联数组中如何判断元素的值为空?
%data=( "a "=> " ", "b "=> " ", "c "=> " ", "d "=> "4 ");
@array=qw(a b c d);
$counter=0;
for ($i=0;$i <=3;$i++)
{
print "$data{$array[$i]}\n ";
if ($data{$array[$i]== " "})
{
$counter++;
}
}
print "$counter\n ";
结果总是:
4
0
[解决办法]
if ($data{$array[$i] eq " "})
或者
unless ($data{$array[$i]})
[解决办法]
一面的方法也许是阁下想要的::
exists EXPR
Given an expression that specifies a hash element or array
element, returns true if the specified element in the hash or
array has ever been initialized, even if the corresponding value
is undefined. The element is not autovivified if it doesn 't
exist.
print "Exists\n " if exists $hash{$key};
print "Defined\n " if defined $hash{$key};
print "True\n " if $hash{$key};
print "Exists\n " if exists $array[$index];
print "Defined\n " if defined $array[$index];
print "True\n " if $array[$index];
A hash or array element can be true only if it 's defined, and
defined if it exists, but the reverse doesn 't necessarily hold
true.