How can I get the index of an element when I grep through an array?

Let's say I have this list:

my @list = qw(one two three four five); 

and I want to capture all elements containing o . I would have this:

 my @containing_o = grep { /o/ } @list; 

But what do I need to do to get the index, or access the index in the grep tag?

+6
arrays grep perl
source share
3 answers

 my @index_containing_o = grep { $list[$_] =~ /o/ } 0..$#list; # ==> (0,1,3) my %hash_of_containing_o = map { $list[$_]=~/o/?($list[$_]=>$_):() } 0..$#list # ==> ( 'one' => 0, 'two' => 1, 'four' => 3 ) 
+15
source share

See List :: MoreUtils . You can do many useful things with arrays without having to run your own version, and also faster (because it is implemented in C / XS):

 use List::MoreUtils qw(first_index indexes); my $index_of_matching_element = first_index { /o/ } @list; 

For all relevant indices, and then their corresponding elements, you can:

 my @matching_indices = indexes { /o/ } @list; my @matching_values = @list[@matching_indices]; 

or simply:

 my @matching_values = grep { /o/ } @list; 
+10
source share

This fills 2 arrays with what you want, scrolling through the input array once:

 use strict; use warnings; my @list = qw(one two three four five); my @containing_o; my @indexes_o; for (0 .. $#list) { if ($list[$_] =~ /o/) { push @containing_o, $list[$_]; push @indexes_o , $_; } } 
+2
source share

All Articles