我想$columns[2]
对照一小串字符串检查数组中的元素。我现在拥有的方式是
if ( $columns[2] eq 'string1'
|| $columns[2] eq 'string2'
|| $columns[2] eq 'string3'
|| ...) {
...
}
似乎必须有一个比所有OR更好的方法。
这恰好grep
是为了:
my $element_exists =
grep { $columns[2] eq $_ } qw(string1 string2 ... stringN);
一种替代方法是使用first
,一旦找到匹配项,它将停止处理。这样,如果您的第一个字符串匹配$columns[2]
,则不必比较其余的n-1个字符串:
use List::Util qw/first/;
my $element_exists =
defined first { $columns[2] eq $_ } qw(string1 string2 ... stringN);
您也可以any
为此目的(如下面的@ThisSuitIsBlackNot建议),略有不同的是,首先返回与条件匹配的元素的值,任何返回布尔值:
use List::Util qw/any/;
my $element_exists =
any { $columns[2] eq $_ } qw(string1 string2 ... stringN);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句