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() ]
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.
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.
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.
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)
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;
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