Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element index in an array in Perl 6

Tags:

raku

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'?

like image 813
chenyf Avatar asked May 09 '18 04:05

chenyf


People also ask

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

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 ..

How do you find the index of an 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?

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.

How do I get the last index of an array in Perl?

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.


2 Answers

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
like image 117
moritz Avatar answered Oct 21 '22 08:10

moritz


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
like image 27
chenyf Avatar answered Oct 21 '22 07:10

chenyf