Perl | exists() Function
Last Updated :
07 May, 2019
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.
@Array = (10, 20, 30, 40, 50);
for ( $i = 0; $i < 10; $i ++)
{
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.
%Hash = ( Mumbai => 1, Kolkata => 2, Delhi => 3);
if ( exists ( $Hash {Mumbai}))
{
print "Exists\n" ;
}
else
{
print "Not Exists\n"
}
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
Please Login to comment...