tags:

views:

58

answers:

4

Hi There!

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 occurrances 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!

A: 

This is perfect for the grep function.

@foo = grep(/cat/, @allMyWords);

EDIT: Excuse my noob. I misread the question.

OmnipotentEntity
That doesn't answer the OPs question at all, they want to know the OFFSETS of EXACT words, not a LIST OF the words that contain a subword.
Kent Fredric
A: 

Possible way:

my $i = 0;
my @indices = map { $_->{index} } 
               grep { $_->{word} eq 'cat' } 
                  map { { word => $_ , index => $i++ } } @allMyWords;

Should do the job. Probably overcomplicated though.

my @indices = grep { defined } map { $i++; $_ eq 'cat' ? $i; undef } @allMyWords

Is a possible improvement.

But theres no good reason in my mind why you can't just use a good-old for-loop.

my @indices;
my $i;
for ( @allMyWords ) {
     push @indicies, $i if $_ eq 'cat';
     $i++;
}

Its probably the most clear implementation.

Kent Fredric
+3  A: 

Hi everyone,

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";   
Radz
But that's a minor issue. Overall this looks like the most elegant method.
Nathan Fellman
+3  A: 

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+/, <>);
Ether