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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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"
    }
}

chevron_right



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.

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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"
}

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.