如何检查 Perl 哈希中是否已存在某个键?
让我们考虑一个场景,我们想知道 Perl 哈希中是否已经包含某个键。在 Perl 中,可以使用 **exists()** 函数来实现。在本教程中,我们将通过两个例子来学习 **exists** 函数。
Perl 中的 exists() 函数
在 Perl 中,**exists()** 函数检查数组或哈希中是否存在特定元素。如果请求的元素出现在输入数组或哈希中,则此函数返回“1”,否则返回“0”。
示例 1
考虑以下代码。在这个例子中,我们将创建一个简单的哈希,然后在下一个例子中,我们将使用 **exists** 函数来检查哈希是否包含特定值。
$countries{'India'} = 12.00;
$countries{'Spain'} = 1.25;
$countries{'Argentina'} = 3.00;
# if the key exists in the hash,
# execute the print statement
if (exists($countries{'Spain'})) {
print "found the key 'Spain' in the hash\n";
} else {
print "could not find the key 'Spain' in the hash\n";
}
输出
如果在 Perl 编译器上运行上述代码,则会在终端上得到以下输出:
found the key 'Spain' in the hash
示例 2
现在,让我们再看一个例子来更好地理解这个概念。考虑以下代码。
# Initialising a Hash
my %Hash = (Spain => 1, India => 2, Russia => 3);
# Calling the exists() function
if (exists($Hash{Spain})) {
print "Spain exists\n";
} else {
print "Spain doesn't exists\n";
}
# Calling the exists() function
# with different parameter
if (exists($Hash{England})) {
print "England exists\n";
} else {
print "England doesn't exist\n";
}
输出
如果在 Perl 编译器上运行此代码,则会在终端上得到以下输出:
Spain exists England doesn't exist
给定的哈希不包含值“England”,因此第二个 exists 函数返回“England doesn't exist”。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP