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()函数以给定的哈希值为参数,检查它是否存在。
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com