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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With