我如何验证值是Perl在阵列(列表)present? [英] How can I verify that a value is present in an array (list) in Perl?
问题描述
我有可能值的列表:
@a = QW(富巴巴兹);
如何在一个简洁的方式将一个值 $ VAL
是present或缺如在检查 @a
?
这是显而易见的实现是遍历列表,但我相信 TMTOWTDI 。
感谢所有谁回答!这三个答案,我想强调的:
-
接受的答案 - 最内置和向后兼容的方式
-
<一个href=\"http://stackoverflow.com/questions/720482/how-to-verify-that-a-value-is-$p$psent-in-an-array-list-in-perl/720530#720530\">RET's回答是最干净的,但只有好为Perl 5.10及更高版本。
-
<一个href=\"http://stackoverflow.com/questions/720482/how-to-verify-that-a-value-is-$p$psent-in-an-array-list-in-perl/720812#720812\">draegtun's答案是(可能)快了一点,但使用一个额外的模块需要。我不喜欢添加依赖,如果我能避开他们,在这种情况下并不需要的性能差异,但如果你有1,000,000元列表中,您可能想给这个答案一试。
Perl的grep的中储存卡()函数是专门做这个。
@matches =的grep(/ ^ $ MyItem /,@someArray);
也可以插入任何Ex pression到匹配
@matches = grep的($ _ == $ VAL,@a);
I have a list of possible values:
@a = qw(foo bar baz);
How do I check in a concise way that a value $val
is present or absent in @a
?
An obvious implementation is to loop over the list, but I am sure TMTOWTDI.
Thanks to all who answered! The three answers I would like to highlight are:
The accepted answer - the most "built-in" and backward-compatible way.
RET's answer is the cleanest, but only good for Perl 5.10 and later.
draegtun's answer is (possibly) a bit faster, but requires using an additional module. I do not like adding dependencies if I can avoid them, and in this case do not need the performance difference, but if you have a 1,000,000-element list you might want to give this answer a try.
Perl's bulit in grep() function is designed to do this.
@matches = grep( /^MyItem$/, @someArray );
or you can insert any expression into the matcher
@matches = grep( $_ == $val, @a );
这篇关于我如何验证值是Perl在阵列(列表)present?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!