How to check if a Perl hash already contains a key?


Let's consider a scenario where we would want to know if a Perl hash already contains a key or not. To do so in Perl, we can use the exists() function. In this tutorial, we will explore the exists function with the help of two examples.

The exists() Function in Perl

In Perl, the exists() function checks whether a particular element exists or not in an array or a hash. If the requested element appears in the input array or hash, this function returns "1", else it returns "0".

Example 1

Consider the code shown below. In this example, we will create a simple hash and then, in the next example, we will use the exists function to check if the hash contains a particular value or not.

$countries{'India'}    = 12.00;
$countries{'Spain'}    = 1.25;
$countries{'Argentina'} = 3.00;

# if the key exists in the hash,
# execute the print statement
if (exists($countries{'Spain'})) {
   print "found the key 'Spain' in the hash\n";
} else {
   print "could not find the key 'Spain' in the hash\n";
}

Output

If you run the above code on a Perl compiler, then you will get the following output on the terminal −

found the key 'Spain' in the hash

Example 2

Now, let's explore one more example to understand the concept even better. Consider the code shown below.

# Initialising a Hash
my %Hash = (Spain => 1, India => 2, Russia => 3);

# Calling the exists() function
if (exists($Hash{Spain})) {
   print "Spain exists\n";
} else {
   print "Spain doesn't exists\n";
}

# Calling the exists() function
# with different parameter
if (exists($Hash{England})) {
   print "England exists\n";
} else {
   print "England doesn't exist\n";
}

Output

If you run this code on a Perl compiler, you will get the following output on the terminal −

Spain exists
England doesn't exist

The given hash does not contain the value "England", hence the second exists function returns "England doesn't exist".

Updated on: 26-Dec-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements