Search code examples
perlarrays

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


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

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


Solution

  • 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;
    

    Outputs:

    item with index 1 in list is 722065