How do I test to see if a Perl hash contains a given key?

By Alvin J. Alexander, devdaily.com

Using Perl, you use the function named exists to see if a key can be found in a hash. Here's the general case of how to search for a given key in a hash:

# already have a hash named %hash and looking
# for a key represented $key

if (exists($hash{$key})) 
{
  # if the key is found in the hash come here
} 
else 
{
  # come here if the key is not found in the hash
}

A concrete example

Here's a more concrete example of this algorithm using a very small hash named people:

# create the hash
%people = ();
$people{"Fred"} = "Flinstone";
$people{"Barney"} = "Rubble";

# specify the desired key
$key = "Fred";

if (exists($people{$key}))
{
  # if the key is found in the hash come here
  print "Found Fred\n";
}
else
{
  # come here if the key is not found in the hash
  print "Could not find Fred\n";
}

When you run this program you'll see that it prints the following output, showing that the key was indeed found in the Perl hash:

Found Fred

devdaily logo