如何檢查 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”。

更新於:2022-12-26

4K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.