Perl exists() 函数

Perl exists() 函数

Perl中的exists()函数用于检查给定数组或哈希中的某个元素是否存在。如果所需元素存在于给定的数组或哈希中,该函数返回1,否则返回0。

语法: exists(Expression)

参数:

Expression: 这个表达式是要调用exists函数的数组或哈希。

返回: 如果所需元素存在于给定的数组或哈希中,则返回1,否则返回0。

例1: 本例在一个数组上使用exists()函数。

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

输出

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

在上面的代码中,可以看到exists()函数的参数是给定数组中每个元素的索引,因此直到索引4(索引从0开始),它给出的输出是 “存在”,然后给出 “不存在”,因为索引已经超出了数组。

例2:这个例子在哈希上使用exists()函数。

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

输出:

Exists
Not Exists

在上面的代码中,exists()函数以给定的哈希值为参数,检查它是否存在。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程