Problem
You need to know whether a hash has a particular key, regardless ofany possible associated value.
Solution
Use the exists
function.
# does %HASH have a value for $KEY ?if (exists($HASH{$KEY})) { # it exists} else { # it doesn't}
Discussion
This code uses exists
to check whether a key is inthe %food_color
hash:
# %food_color per the introductionforeach $name ("Banana", "Martini") { if (exists $food_color{$name}) { print "$name is a food.\n"; } else { print "$name is a drink.\n"; }}
Banana is a food.
Martini is a drink.
The exists
function tests whether a key is in thehash. It doesn’t test whether the value corresponding to thatkey is defined, nor whether the value is true or false. We may besplitting hairs, but problems caused by confusing existence,definedness, and truth can multiply like rabbits. Take this code:
%age = ();$age{"Toddler"} = 3;$age{"Unborn"} = 0;$age{"Phantasm"} = undef;foreach $thing ("Toddler", "Unborn", "Phantasm", "Relic") { print "$thing: "; print "Exists " if exists $age{$thing}; print "Defined " if defined $age{$thing}; print "True " if $age{$thing}; print "\n";}
Toddler: Exists Defined True
Unborn: Exists Defined
Phantasm: Exists
Relic:
$age{"Toddler"}
passes the existence, definedness,and truth tests. It exists because we gave"Toddler"
a value in the hash, it’s definedbecause that value isn’t undef
, andit’s true because the value isn’t one of Perl’sfalse values.
$age{"Unborn"}
passes ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.