Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of an element in an array?

Tags:

perl

Does Perl have a build-in function to get the index of an element in an array? Or I need write such a function by myself? [ equivalent to PHP array_search() or JavaScript array.indexOf() ]

like image 530
powerboy Avatar asked Jul 11 '10 06:07

powerboy


People also ask

How do you get the index of an item in an array Java?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

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

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.

How do I print the index of an array?

You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.

Is there an indexOf for arrays?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.


2 Answers

use List::Util qw(first); $idx = first { $array[$_] eq 'whatever' } 0..$#array; 

(List::Util is core)

or

use List::MoreUtils qw(firstidx); $idx = firstidx { $_ eq 'whatever' } @array; 

(List::MoreUtils is on CPAN)

like image 91
hobbs Avatar answered Sep 19 '22 19:09

hobbs


Here's a post-5.10 way to do it, with the added benefit of determining how many indexes match the given value.

my @matches = grep { $array[$_] ~~ $element } 0 .. $#array; 

If all elements are guaranteed to be unique, or just the first index is of interest:

my ($index) = grep { $array[$_] ~~ $element } 0 .. $#array; 
like image 45
Zaid Avatar answered Sep 18 '22 19:09

Zaid