12/12/2017 - 11:00 AM

Hash key existence

The 'exists' operator returns a boolean value to indicate whether a hash contains a key. Its useful because it avoids checking the boolean nature of a hash value, meaning a hash key can exist even if its value is a boolean false (i.e undef). Also, 'exists' doesn't use autovivification within nested data structures.

# Simple example:

if (exists $books{"dino"}) { # checks if the key exists
  print "Hey, there's a library card for Dino!\n";

# More complex example:

my %addresses = (
    Leonardo => '1123 Fib Place',
    Utako    => 'Cantor Hotel, Room 1',
  say "Have Leonardo's address" if exists $addresses{Leonardo}; # true
  say "Have Warnie's address" if exists $addresses{Warnie}; # false
  # if a hash key exists, its value may be undef, to check that: 
  $addresses{Leibniz} = undef;
  say "Gottfried lives at $addresses{Leibniz}"
    if exists $addresses{Leibniz} && defined $addresses{Leibniz}; # say string if the hash key exists and its value is defined