Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching unsorted array in perl?

Tags:

arrays

perl

I have an array with... lets say 100 elements. I want to check to see if any of the elements matches a particular string. For example:

@array = ('red','white','blue');

I also want to know if the array contains the string 'white' as one of the elements. I know how to do this with a foreach loop and comparing each element, but... is there an easier (faster) way than looping through the whole array?

-Thanks

like image 275
Nate the Noob Avatar asked Feb 21 '26 06:02

Nate the Noob


1 Answers

Perl 5.10 and higher, smart match:

say 'found' if 'white' ~~ @array;

For pre-5.10, List::MoreUtils:

use List::MoreUtils qw{any}; 
print "found" if any { 'white' eq $_ } @array;

These short circuit - if a match is found there is no need to traverse the whole array.

like image 188
martin clayton Avatar answered Feb 23 '26 23:02

martin clayton