Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Good way to test if a value is in an array?

Tags:

arrays

perl

If I have an array:

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

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

like image 487
coding4fun Avatar asked Dec 31 '10 14:12

coding4fun


People also ask

How do you check if a certain value is in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.

Which one is the correct way of accessing array elements in Perl?

Perl Array Accessing To access a single element of a Perl array, use ($) sign before variable name. You can assume that $ sign represents singular value and @ sign represents plural values. Variable name will be followed by square brackets with index number inside it.

What does ~~ mean in Perl?

It is the smartmatch operator. In general, when you want information about operators in Perl, see perldoc perlop. Follow this answer to receive notifications.


1 Answers

You can't without looping. 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 ) ...

Before using smartmatch, note:

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

like image 64
ysth Avatar answered Oct 18 '22 09:10

ysth