作者:摇身一变鄙人 | 来源:互联网 | 2023-02-05 14:22
我有一个包含几个单词的文件,让我们以此文件为例:
balloon
space
monkey
fruit
我想检查字符串是否包含至少一个这样的单词.我将所有单词存储在数组中,如下所示(文件在参数中指定):
open my $exampleFile, '<', $ARGV[0];
chomp(my @exampleWords= <$exampleFile>);
close $exampleFile;
然后我用它grep
来检查这些单词中是否有一个在字符串中:
if ( grep( $string, @exampleWords ) )
{
#do something
}
如果我以字符串为例this_is_a_balloon_example
,balloon
已经找到了这个单词,所以我应该进入循环.目前,似乎为任何给定的字符串输入循环.
1> Sobrique..:
grep
迭代一个列表.结果可能是相当低效的.
我建议你想要做的是编译一个正则表达式.
my $regex = join "|", @examplewords;
$regex = qr/\b($regex)\b/;
if ( $string =~ m/$regex/ ) {
print "There was a match on $1\n";
}
2> Сухой27..:
你grep
正在检查真正的价值,而且$string
几乎总是"真实的".你需要的是正则表达式,它测试是否$string
匹配$_
,
if ( grep($string =~ /$_/, @exampleWords ) )
{
#do something
}