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?
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.
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.
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.
You can use Grep to filter enumerable objects, like Arrays & Ranges.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With