SPUG: IndexOf in Perl?

DeRykus, Charles E charles.e.derykus at boeing.com
Sat Jan 28 13:46:42 PST 2006


 

> 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".

There are several ways to do this in Perl of course but if you 
wanted an IndexOf lookalike:

sub IndexOf {     # pass in value, array reference
   my ( $value, $arrayref ) = ( shift, shift );
   foreach my $i ( 0 .. @$arrayref-1 )  {
      return $i if $$arrayref[$i] == $value;
   }
}

Example:   $index = IndexOf( 25,  \@array );

* I'm assuming numeric arrays so '==' is used instead of 'eq' 
 
* IndexOf returns an undefined value if the value isn't found


hth,
-- 
Charles DeRykus


More information about the spug-list mailing list