in reply to Simple things should be coded simply (Re: Idiomatic Array Index Search?)
in thread Idiomatic Array Index Search?

I agree with all the above (simple things simple etc.) but am wondering what happens if you have two matching elements. I don't remember anybody saying they were unique, and an array just looks like a set when you use qw() but it isn't one mathematically.

So maybe you should return an array, sorted of course.

Then may I propose the most idiomatic would be to use another language, SQL of course? I am thinking of DBD::RAM. You could say something like

print $dbh->selectcol_arrayref(qq [ SELECT phrase FROM my_phrases WHERE id = 1 ORDER BY phrase ])->[0];

Some other neat looking modules may include Search::InvertedIndex, Search::Binary, and Math::IntervalSearch (Search where an element lies in a list of sorted elements).

..to answer japhy and merlyn below, honored to join this thread with you both. To be sure, grep is good. Thank you for your elegant code.

  • Comment on Re: Simple things should be coded simply (Re: Idiomatic Array Index Search?)
  • Download Code

Replies are listed 'Best First'.
Re: Re: Simple things should be coded simply (Re: Idiomatic Array Index Search?)
by japhy (Canon) on May 28, 2001 at 19:21 UTC
    Then grep() would be a super choice:
    sub get_index { my ($a, $e) = @_; my @idx = grep $a->[$_] eq $e, 0 .. $#$a; return wantarray ? @idx : $idx[0]; }


    japhy -- Perl and Regex Hacker