By Alvin Alexander. Last updated: June 4, 2016
Perl hash key FAQ: How do I test to see if a Perl hash containts a given key?
You can use the Perl exists function 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 perl hash named %hash, and looking
# for a key represented by $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 more complete Perl hash key example
Here's a more complete example of this Perl hash key algorithm, using a very small Perl hash named people:
# create our perl 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 our Perl hash:
Found Fred
Related Perl hash tutorials
I hope you found this short Perl hash tutorial helpful. We have many more Perl hash tutorials on this site, including the following:
Getting started Perl hash tutorials:
- Perl hash introduction/tutorial
- Perl foreach and while: how to loop over the elements in a Perl hash
- Perl hash add - How to add an element to a Perl hash
- How to print each element in a Perl hash
More advanced Perl hash tutorials:
The hash in Perl - hash sorting tutorials:

