The Perl exists function - test to see if a hash key exists

Perl "hash key exists" FAQ: How can I test to see if a key exists in a Perl hash?

Many times when working with a Perl hash, you need to know if a certain key already exists in the hash. The Perl exists function lets you easily determine if a key already exists in the hash.

A Perl hash key exists example

Here's a simple example that demonstrates the Perl "exists" hash function. In this Perl script we'll first create a simple Perl hash, and then we'll use the exists function to see if the hash key named 'coke' exists in the hash.

First, we create a simple Perl hash:

# create a perl hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

Next, we use the Perl exists function to see if the key exists in our Perl hash:

# if the key exists in the hash,
# execute the print statement
if (exists($prices{'coke'}))
{
  print "found the key 'coke' in the hash\n";
}

As you can see from the code, the hash key coke does indeed exist, so the Perl print statement shown will be executed.

Of course this example is very simple, but I hope it helps to demonstrate the Perl exists function in combination with a key in a Perl hash.

Related "hash in Perl" 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: