Mat*_*hew 1 perl string-matching
我想$columns[2]根据一小组字符串检查数组中的元素.我现在的方式是;
if ( $columns[2] eq 'string1'
|| $columns[2] eq 'string2'
|| $columns[2] eq 'string3'
|| ...) {
...
}
Run Code Online (Sandbox Code Playgroud)
似乎必须有比所有OR更好的方法.
这正是grep为了:
my $element_exists =
grep { $columns[2] eq $_ } qw(string1 string2 ... stringN);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用first,一旦找到匹配就会停止处理.这样,如果您首先匹配字符串$columns[2],则不必比较剩余的n-1个字符串:
use List::Util qw/first/;
my $element_exists =
defined first { $columns[2] eq $_ } qw(string1 string2 ... stringN);
Run Code Online (Sandbox Code Playgroud)
你也可以any(为@ThisSuitIsBlackNot建议在下面)为此目的,稍微区别是首先返回匹配条件的元素的值,any返回一个布尔值:
use List::Util qw/any/;
my $element_exists =
any { $columns[2] eq $_ } qw(string1 string2 ... stringN);
Run Code Online (Sandbox Code Playgroud)