Perl: find the index of an array item

I needed to find the index of an item in an array so I wrote a simple Perl function.

sub array_id {
   my ($needle,@haystack) = @_;
   my $count = 0;

   foreach my $item (@haystack) {
      if ($item eq $needle) {
         return $count;
      }

      $count++;
   }

   return -1;
}
Leave A Reply - 1 Reply
Replies
Steven Haryanto 2013-10-18 03:26am - stevenharyanto@gmail.com - Logged IP: 203.130.198.32

Take a look at List::MoreUtils' firstidx().

All content licensed under the Creative Commons License