Open In App

Perl | exists() Function

The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

Syntax: exists(Expression)



Parameters:
Expression : This expression is either array or hash on which exists function is to be called.

Returns: 1 if the desired element is present in the given array or hash else returns 0.



Example 1: This example uses exists() function over an array.




#!/usr/bin/perl 
  
# Initialising an array
@Array = (10, 20, 30, 40, 50);
  
# Calling the for() loop over
# each element of the Array
# using index of the elements
for ($i = 0; $i < 10; $i++)
{
      
    # Calling the exists() function
    # using index of the array elements
    # as the parameter
    if(exists($Array[$i]))
    {
        print "Exists\n";
    }
    else
    {
        print "Not Exists\n"
    }
}


Output:

Exists
Exists
Exists
Exists
Exists
Not Exists
Not Exists
Not Exists
Not Exists
Not Exists

In the above code, it can be seen that parameter of the exists() function is the index of each element of the given array and hence till index 4 (index starts from 0) it gives output as “Exists” and later gives “Not Exists” because index gets out of the array.

Example 2: This example uses exists() function over a hash.




#!/usr/bin/perl 
  
# Initialising a Hash
%Hash = (Mumbai => 1, Kolkata => 2, Delhi => 3);
  
# Calling the exists() function
if(exists($Hash{Mumbai}))
{
    print "Exists\n";
}
else
{
    print "Not Exists\n"
}
  
# Calling the exists() function
# with different parameter
if(exists($Hash{patna}))
{
    print "Exists\n";
}
else
{
    print "Not Exists\n"
}

Output :

Exists
Not Exists

In the above code, exists() function takes the key of the given hash as the parameter and check whether it is present or not.


Article Tags :