SPUG: IndexOf in Perl?

David Dyck david.dyck at fluke.com
Sat Jan 28 15:32:40 PST 2006

On Sat, 28 Jan 2006 at 11:58 -0800, Tanwir Habib <tanwirh at hotmail.com> wrote:

> I've recently switched from .NET to Perl for my needs in
> bioinformatics work.
> Is there a way in Perl to search an array with its value to get its
> index? like java does with "IndexOf".

Look at List::MoreUtils

perl -le 'use List::MoreUtils qw(firstidx); print firstidx { /z/ } ("a" .."z");'

firstidx BLOCK LIST
first_index BLOCK LIST

     Returns the index of the first element in LIST for which the criterion
     in BLOCK is true. Sets $_ for each item in LIST in turn:

         my @list = (1, 4, 3, 2, 4, 6);
         printf "item with index %i in list is 4", firstidx { $_ == 4 } @list;
         item with index 1 in list is 4

     Returns -1 if no such item could be found.

     first_index is an alias for firstidx.

More information about the spug-list mailing list