Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I find the index of a given value in an array?

Tags:

arrays

perl

$VAR1 = [
          '830974',
          '722065',
          '722046',
          '716963'
        ];

How can I calculate the array index for the value "722065"?

like image 577
Antonio Lopes Avatar asked Dec 16 '09 16:12

Antonio Lopes


People also ask

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

Perl access array elements Array elements are access by their indexes. The first index has value 0. The last index is $#vals . Array elements can be accessed from the end by using negative indexes.

How do you find the index of a value in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How do I extract an element from an array in Perl?

Arrays can store any type of data and that data can be accessed in multiple ways. These values can be extracted by placing $ sign before the array and storing the index value of the element to be accessed within the square brackets.


1 Answers

The firstidx function from List::MoreUtils can help:

use strict;
use warnings;
use List::MoreUtils qw(firstidx);

my @nums = ( '830974', '722065', '722046', '716963' );
printf "item with index %i in list is 722065\n", firstidx { $_ eq '722065' } @nums;

__END__
item with index 1 in list is 722065
like image 75
toolic Avatar answered Oct 11 '22 18:10

toolic