Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I also get an element's index when I grep through an array?

Tags:

arrays

grep

perl

Let's say I have this list:

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

and I want to grab all the elements containing o. I'd have this:

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

But what would I have to do to also receive an index, or to be able to access the index in grep's body?

like image 245
Geo Avatar asked Jun 10 '10 16:06

Geo


People also ask

Can you access an element in an array by using its index?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you find the index of a particular element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you find the index of an element in an array in Shell?

To find the index of specified element in an array in Bash, use For loop to iterate over the index of this array. In the for loop body, check if the current element is equal to the specified element. If there is a match, we may break the For loop and we have found index of first occurrence of specified element.

Can you grep an array?

You can use Grep to filter enumerable objects, like Arrays & Ranges.


1 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 )
like image 112
mob Avatar answered Oct 08 '22 03:10

mob