9

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

2
  • 1
    Awesome! In cases like this, you can post both a question and an answer at the same time. Commented May 9, 2018 at 12:28
  • yes. I will. Thanks. Commented May 9, 2018 at 15:03

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.