To get the index of a specified element in an array in Perl, you can use functions like first_index
from the List::MoreUtils module or first
from the List::Util module.
In this example,
first_index
function from the List::MoreUtils module to find the index of element 30 in the array.first_index
function returns the index of the first occurrence of the element, or -1 if the element is not found.use List::MoreUtils qw(first_index);
my @arr = (10, 20, 30, 40, 50);
my $index = first_index { $_ == 30 } @arr;
print "Index of element 30 is: $index\n";
Index of element 30 is: 2
In this example,
first
function from the List::Util module to find the index of element 60 in the array.first
function returns the first element for which the block returns true, or undef if no element is found.use List::Util qw(first);
my @arr = (10, 20, 30, 40, 50);
my $index = first { $_ == 60 } @arr;
print "Index of element 60 is: ", defined $index ? $index : 'Element not found', "\n";
Index of element 60 is: Element not found
In this tutorial, we learned How to get the Index of Specified Element in an Array in Perl language with well detailed examples.