Perl Get indexes of matches in an array

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

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

$myWord = cat

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

So, if a cat is found at the 3rd, 19th and 110th positions, I want to get these indices as a result of this. I was wondering if there is a small and easy way to do this.

Thank!

+3
source share
2 answers

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

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

With List :: MoreUtils :

use List::MoreUtils qw(indexes);

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

If you have not read the file yet, you can read it using the slurp mode:

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

Source: https://habr.com/ru/post/1771865/


All Articles