如何验证 Perl 中的数组(列表)中是否存在值? [英] How can I verify that a value is present in an array (list) in Perl?

查看:84
本文介绍了如何验证 Perl 中的数组(列表)中是否存在值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能值的列表:

I have a list of possible values:

@a = qw(foo bar baz);

如何以简洁的方式检查值 $val@a 中是否存在?

How do I check in a concise way that a value $val is present or absent in @a?

一个明显的实现是遍历列表,但我确信TMTOWTDI.

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:

  1. 公认的答案 - 最内置"和向后兼容的方式.

  1. The accepted answer - the most "built-in" and backward-compatible way.

RET 的答案 是最干净的,但仅适用于 Perl 5.10 及更高版本.

RET's answer is the cleanest, but only good for Perl 5.10 and later.

draegtun 的答案(可能)快一点,但需要使用额外的模块.如果我可以避免它们,我不喜欢添加依赖项,并且在这种情况下不需要性能差异,但是如果您有一个 1,000,000 个元素的列表,您可能想尝试一下这个答案.

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 内置的 grep() 函数就是为此而设计的.

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 中的数组(列表)中是否存在值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆