Regex 检查';散列键字符串';在perl中包含一个单词
我想检查哈希键中是否存在特定的单词 我尝试了以下方法:Regex 检查';散列键字符串';在perl中包含一个单词,regex,perl,perl-hash,Regex,Perl,Perl Hash,我想检查哈希键中是否存在特定的单词 我尝试了以下方法: while (($key, $value) = each(%hash)) { if( $key =~ /\b$some_word\b/ ) { print"$key contains $some_word \n"; } } 我的问题是,是否有相同的内置函数,或者是否有其他方法 use warnings; use strict; my %hash = ( 'foo' => 1, 'f
while (($key, $value) = each(%hash))
{
if( $key =~ /\b$some_word\b/ )
{
print"$key contains $some_word \n";
}
}
我的问题是,是否有相同的内置函数,或者是否有其他方法
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:感谢kenosis建议使用quote-literal修饰符(
\Q..\E
),这通常是将变量放入正则表达式时的一个好主意。它确保变量中没有任何内容被解释为regex元字符。切换操作数:$key=~/\b$some\u word\b/
@Linus Kleen:Pheww:p这是一个打字错误。非常感谢。我在问题中更正了它。