in reply to Finding index of an entry in an Array

if you are doing a sufficiently large number of look-ups in the  @repo array, it will be advantageous to do a cached look-up of the index. (this will be all the more true if the array is large.)

perl -wMstrict -e "my @repo = qw(foo bar qux bar zot); my %repo_index; $repo_index{$repo[$_]} = $_ for reverse 0 .. $#repo; print $repo_index{bar};" 1

note that if there are duplicate entries in the array, the index of the first (lowest index) entry will be returned. eliminate the  reverse call to have it the other way.

Replies are listed 'Best First'.
Re^2: Finding index of an entry in an Array
by jrsimmon (Hermit) on Dec 07, 2007 at 03:52 UTC
    note that if there are duplicate entries in the array, the index of the first (lowest index) entry will be returned. eliminate the reverse call to have it the other way.
    This should be restated to say exactly two duplicate entries. A third or further duplicates would be undetectable with this method.
      i don't understand your point. i would not say my approach was able to directly detect any number of duplicates, whether 2, 3 or more. (the only, and somewhat awkward, way to detect the presence of duplicates with this specific caching approach would be to build two caches, one based on ascending indices, the other based on descending indices, and compare the two indices derived from the two caches. if they are not the same, two or more duplicates must exist. however, i can think of better ways to handle this sort of info.)

      the point i was trying, perhaps clumsily, to make in my original post was that my method, in common with all the other approaches that had appeared by then, would, due to the use of reverse, return the first (i.e., lowest) index of a match in the case of duplicates, but that a variation could easily be had that would return the last/highest index.

      since my original post, i see that some solutions have been posted that return the indices of all matches, which i did not understand to be a requirement of the original question. oh, well...