Open In App

Perl | exists() Function

Last Updated : 07 May, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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.






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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads