Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 检查';散列键字符串';在perl中包含一个单词_Regex_Perl_Perl Hash - Fatal编程技术网

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这是一个打字错误。非常感谢。我在问题中更正了它。