How can I find the index of an element within an array?
For example, given
my @weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
How could I find the index for 'Thursday'
?
Also, first will exit the implicit loop upon finding the index that matches. The grep equivalent would be $idx = grep { $array[$_] eq 'whatever' and last } 0 ..
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.
indexOf() The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.
You can use first
(or grep
, if you want to know about all matches, not just the first one) with :k
to return the key (which for a list is always an Integer index) instead of the value:
say @weekdays.first('Tuesday', :k); # 1
My initial solution:
@weekdays.kv.reverse.hash.{'Thursday'} # 3
Then JFerrero posted his improvement solution using antipairs:
@weekdays.antipairs.hash.{'Thursday'} # 3
And ultimatto posted an adverb solution:
@weekdays.first('Thursday', :k) # 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