chenyf
chenyf

Reputation: 5058

Find element index in an array in Perl 6

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

Upvotes: 9

Views: 506

Answers (2)

moritz
moritz

Reputation: 12852

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

Upvotes: 8

chenyf
chenyf

Reputation: 5058

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

Upvotes: 9

Related Questions