在字符串或整个文件中搜索数组元素出现的 Perl 习语是什么?例如:
my @array = qw(word, test, ...);
my $string = ".......";
我要搜索word
或test
(也可以是words
、tester
等)在 $string
中并返回找到的任何内容(即组匹配)。
我搜索了文档,似乎 map + grep
是我需要的,但我就是想不出它的代码。 Perl 是如此有趣,以至于我有时完全无能为力。 :)
使用 map
中的一个示例:
my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;
我想我可以将字符串拆分为数组和 grep
。我说得对吗?
grep { @array } @string; # something like grep {/(word|test)/} @string but I want to use array
最佳答案
my @word_roots = qw( word test );
my $pat = join '|', map quotemeta, @word_roots;
my $re = qr/\b(?:$pat)\w+\b/;
my @matches = $string =~ /($re)/g;
关于regex - 使用数组中的元素快速搜索文件的 Perl 习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20794043/