Hash Keys and Values

Learn how to check for the existence of hash keys and how to access them.

Checking hash key existence

The exists operator returns a boolean value to indicate whether a hash contains the given key:

Press + to interact
my %addresses = (
Leonardo => '1123 Fib Place',
Utako => 'Cantor Hotel, Room 1'
);
say "Have Leonardo's address" if exists $addresses{Leonardo};
say "Have Warnie's address" if exists $addresses{Warnie};

Using exists instead of accessing the hash directly avoids two problems. First, it doesn’t check the boolean nature of the hash value; a hash key may exist with a value even if that value evaluates to a boolean false (including undef):

Press + to interact
use Test::More;
my %false_key_value = ( 0 => '' );
ok %false_key_value,
'hash containing false key & value should evaluate to a true value';
done_testing();

Second, exists avoids autovivificationAuto-creation of nested data structures on demand. ...