Perl的:良好的方式来测试,如果值是一个数组? [英] Perl: Good way to test if a value is in an array?

查看:91
本文介绍了Perl的:良好的方式来测试,如果值是一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数组:

@int_array = (7,101,80,22,42);

我如何检查是否整数值80是在阵列中,而无需通过每一个元素循环?

How can I check if the integer value 80 is in the array without looping through every element?

推荐答案

您不能。这意味着什么是一个数组的一部分。您可以使用使用grep或smartmatch一个隐含的循环,但还是有一个循环。如果你想避免环路,使用哈希代替(或补充)。

You can't. That's part of what it means to be an array. You can use an implicit loop using grep or smartmatch, but there's still a loop. If you want to avoid the loop, use a hash instead (or in addition).

# grep
if ( grep $_ == 80, @int_array ) ...

# smartmatch
use 5.010001;
if ( 80 ~~ @int_array ) ...

使用smartmatch前,请注意:

Before using smartmatch, note:

<一个href=\"http://search.cpan.org/dist/perl-5.18.0/pod/perldelta.pod#The_smartmatch_family_of_features_are_now_experimental\">http://search.cpan.org/dist/perl-5.18.0/pod/perldelta.pod#The_smartmatch_family_of_features_are_now_experimental:

的特征的smartmatch系列现已实验

智能匹配,加入v5.10.0和v5.10.1显著修订,一直投诉正规点。虽然有许多方法,其中它是有用的,它也被证明为Perl的两个用户和实现问题和混乱。已经有一些关于如何最好地解决问题的建议。很显然,smartmatch几乎可以肯定是要么将改变或消失的未来。不建议依托其当前的行为。

Smart match, added in v5.10.0 and significantly revised in v5.10.1, has been a regular point of complaint. Although there are a number of ways in which it is useful, it has also proven problematic and confusing for both users and implementors of Perl. There have been a number of proposals on how to best address the problem. It is clear that smartmatch is almost certainly either going to change or go away in the future. Relying on its current behavior is not recommended.

在解析器看到警告~~现在将发出,给予,或当。要禁用这些警告,您可以将此行添加到适当范围

Warnings will now be issued when the parser sees ~~, given, or when. To disable these warnings, you can add this line to the appropriate scope

这篇关于Perl的:良好的方式来测试,如果值是一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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