Nate the Noob
Nate the Noob

Reputation: 370

Searching unsorted array in 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

Upvotes: 2

Views: 375

Answers (4)

mob
mob

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

martin clayton
martin clayton

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

codaddict
codaddict

Reputation: 454922

You can use grep as:

@array = ('red','white','blue');
$key = 'white';
if (grep { $_ eq $key } @array) {
        print $key.' found';
} 

Upvotes: 3

moinudin
moinudin

Reputation: 138317

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

Upvotes: 1

Related Questions