Radz
Radz

Reputation: 543

perl Get indexes of matches in array

I want to search for an element in an array. What I want to get from this search is the all the indices of the array where I find a match.

So, for example the word I want to search is :

$myWord = cat

@allMyWords = my whole file with multiple occurrences of cat in random positions in file

So, if cat occurs at 3rd, 19th and 110th position, I want those indices as a result of it. I was wondering if there is a small and simple method to do this.

Thanks!

Upvotes: 4

Views: 12627

Answers (2)

Radz
Radz

Reputation: 543

I got the answer. This is the code that will return all the indices in the array where an element we are searching for is found.

my( @index )= grep { $allMyWords[$_] eq $word } 0..$#allMyWords;
print "Index : @index\n";   

Upvotes: 12

Ether
Ether

Reputation: 53966

With List::MoreUtils:

use List::MoreUtils qw(indexes);

my @indexes = indexes { $_ eq 'cat' } @words;

If you haven't read the file yet, you can read it using "slurp mode":

local $/; # enable slurp mode
my @words = split(/\s+/, <>);

Upvotes: 11

Related Questions