数组 – Perl:测试数值是否在数组中的好方法?

前端之家收集整理的这篇文章主要介绍了数组 – Perl:测试数值是否在数组中的好方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个数组:
@int_array = (7,101,80,22,42);

如何在数组中检查整数值80是否不循环遍历每个元素?

解决方法

你不行这是数组意味着什么的一部分.你可以使用一个使用grep或smartmatch的隐式循环,但仍然有一个循环.如果你想避免循环,使用哈希(或另外).
# grep
if ( grep $_ == 80,@int_array ) ...

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

在使用smartmatch之前,请注意:

http://search.cpan.org/dist/perl-5.18.0/pod/perldelta.pod#The_smartmatch_family_of_features_are_now_experimental

The smartmatch family of features are now experimental

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相关文章