2012-12-12 51 views
2

我想檢查一個特定的字是否存在於哈希鍵中。檢查'哈希鍵字符串'是否包含perl中的一個字

我試圖以下列方式:

while (($key, $value) = each(%hash)) 
{ 
    if($key =~ /\b$some_word\b/) 
    { 
     print"$key contains $some_word \n"; 
    } 
} 

我的問題是有同樣的任何內置功能或者是有什麼替代方法?

+0

開關操作數:'$ key =〜/ \ b $ some_word \ b /'。 –

+0

@Linus Kleen:Pheww:P那是一個錯字。謝謝。我在問題中糾正了它。 –

回答

4
use warnings; 
use strict; 

my %hash = (
    'foo' => 1, 
    'foo bar' => 2, 
    'bar' => 3, 
    'food' => 4 
); 

my $some_word = "foo"; 

for (grep /\b\Q$some_word\E\b/, keys %hash) 
{ 
    print "$_ contains $some_word (value: $hash{$_})\n" 
} 

更新:包括價值爲好。

更新2:感謝,虛己,提出了這個報價字面修飾符(\Q...\E),這通常是一個好主意,把一個變量爲正則表達式時。它確保變量中的任何內容都不會被解釋爲正則表達式元字符。

+0

謝謝......這有幫助。 –

+1

'/ \ b \ Q $ some_word \ E \ b \'以防萬一...... – Kenosis

相關問題