Perl: How to test if any value (even zero) has been assigned to a hash key
Is there a correct way of testing开发者_如何学运维 if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:
%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }
but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?
Use the defined operator to check if something has value which is not undef
if ( defined $hash{ $key } ) {
//do stuff
}
Use the exists operator to check if a $key
of a %hash
has been written to
if ( exists $hash{ $key } ) {
//do stuff
}
The difference being that defined
checks to see if a value is of anything other than undef
and exists
is used to verify if $key
is a key of the hash despite its value.
See perldoc -f defined
and perldoc -f exists
:
my %hash = (foo => 0, bar => undef);
print defined $hash{foo}; # true
print defined $hash{bar}; # false
print exists $hash{bar}; # true
print exists $hash{baz}; # false
delete $hash{bar};
print exists $hash{bar}; # false
You can use defined()
to check if the key actually exists in the hash:
if (defined($hash{$key})) { do('something'); };
精彩评论