Date: Tue, 3 Jul 2001 14:51:47 -0400
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Finding the subscript of an item in an array...
Message-Id: <slrn9k4523.avt.tadmc@tadmc26.august.net>

Weston Cann <iowa_song88.remove_eights_and_this@hotmail.com> wrote:

>I know that you can find the subscript of an item in an array by
>doing something like this:
>
>
>my @foo = ('Travis','Bonnie','Flipper','Arnold','Deluxe');
>my $item = 'Flipper';
>
>my $index = 0;
>my $subscript;


   my($subscript) = grep { $item eq $foo[$_]} 0 .. $#foo;

or, make a hash that maps the term to its index number:

   my $i;
   my %foo = map { $_, $i++ } @foo;  # or @foo{ @foo } = 0 .. $#foo;
   my $subscript = $foo{$item};


>while($index <= $#foo)
>{
>   if($item eq $foo[$index])
>   { $subscript = $index; }

    { $subscript = $index; last; }

If there cannot be duplicates, then might as well stop looking
when one is found. The grep() above and your original code
both look through the entire array every time.


>   $index++;
>}
>
>
>
>This is OK, but it's sortof bulky. I'm wondering if there's a neat-o
>perl idiom/single line kind of way to do the same thing.


You leave a lot of things unspecified, so we can't give directly
applicable help.

Does the order of the array elements matter? 

Can there be duplicated elements? If so, report first/last/all indexes?

What should it do when the item is NOT found?

 ...

When you "need to know the index" you can often redesign your code
so that you do not need to know it (eg. put the strings in a hash as
suggested by "perldoq -q contains"). Don't know if you can do that
or not 'cause you haven't spec'd your circumstances very thoroughly.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


