Perl hash key - How to test to see if a Perl hash contains a given key

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:

More advanced Perl hash tutorials:

The hash in Perl - hash sorting tutorials:

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.