2

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

Nate the Noob
  • 370
  • 2
  • 5
  • 16
  • 2
    Because it's unsorted, any method you find is going to involve searching the whole array, so it's not going to be faster than looping through it. – Paul Tomblin Dec 21 '10 at 13:39
  • 1
    See: http://stackoverflow.com/questions/3951812/how-fast-is-perls-smart-match-operator-for-searching-scalar-in-an-array – martin clayton Dec 21 '10 at 13:42

4 Answers4

6

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.

martin clayton
  • 76,436
  • 32
  • 213
  • 198
3

You can use grep as:

@array = ('red','white','blue');
$key = 'white';
if (grep { $_ eq $key } @array) {
        print $key.' found';
} 
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • Thank you for also posting about "grep" but also thank-you for showing an example of how I would use it within my code. – Nate the Noob Dec 21 '10 at 13:33
2

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";
}
mob
  • 117,087
  • 18
  • 149
  • 283
1

It won't be any faster than looping, but you can use grep within Perl.

$ perl -e "@array = ('red','white','blue'); print grep(/^white$/, @array);"
white
moinudin
  • 134,091
  • 45
  • 190
  • 216