user900889
user900889

Reputation: 75

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 ?

Upvotes: 3

Views: 6461

Answers (3)

zellio
zellio

Reputation: 32484

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.

Upvotes: 10

zoul
zoul

Reputation: 104065

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

Upvotes: 5

Jack M.
Jack M.

Reputation: 32070

You can use defined() to check if the key actually exists in the hash:

if (defined($hash{$key})) { do('something'); };

Upvotes: -2

Related Questions