in reply to array index

grep on the index.
my $search = 'foo'; my ($where) = grep { $question[$_] eq $search } 0 .. $#question;

If you have to do this very often with the same array, it might be better to build a lookup hash. Hash lookup is very fast.

# once: my %lookup; @lookup{@question} = ( 0 .. $#question ); # many times: my $search = 'boo'; $where = $lookup{$search};

Replies are listed 'Best First'.
Re^2: array index
by monkeybus (Acolyte) on May 20, 2007 at 07:14 UTC
    Thanks a lot, but what if @question = "foo doo doo"? Is there a way that I can return more than one array index?
      You could extend bart's hash lookup by building a hash of arrays.
      #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @list = qw{one two three four one}; my %lookup; for my $i (0..$#list){ push @{$lookup{$list[$i]}}, $i; } print "@{$lookup{one}}\n"; #print Dumper \%lookup;
      grep returns all matching indexes, I just ignored all but the first one. That's easily fixed:
      my @where = grep { $question[$_] eq $search } 0 .. $#question;

      Using a hash for lookup is a not so dead simple adaptation, but still feasible. In the meantime, wfsp has shown how it can be done.