Reputation: 370
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
Upvotes: 2
Views: 375
Reputation: 118595
If you are going to search the array many times, it would be worth while to build a hash table of your array data:
my %array_data = map { $array[$_] => $_ } 0..$#array;
my $search_term = 'white';
if (defined $array_data{$search_term}) {
print "'$search_term' was found at array index $array_data{$search_term}\n";
}
Upvotes: 2
Reputation: 78105
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.
Upvotes: 6
Reputation: 454922
You can use grep
as:
@array = ('red','white','blue');
$key = 'white';
if (grep { $_ eq $key } @array) {
print $key.' found';
}
Upvotes: 3