monkeybus has asked for the wisdom of the Perl Monks concerning the following question:

Hello, suppose @question holds "foo boo doo" so $question[0] = foo and so on. What if I know foo is in the array and I want to return the corresponding index number? Or the index for boo or doo? I can grep to see if foo is in there, but I want to know exactly where it is located in the array. Thanks a lot, this is the first programming I have done since I had my Commodore64 20 odd years ago.

Replies are listed 'Best First'.
Re: array index
by bart (Canon) on May 20, 2007 at 06:58 UTC
    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};
      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.

Re: array index
by blazar (Canon) on May 20, 2007 at 15:00 UTC
    Hello, suppose @question holds "foo boo doo" so $question[0] = foo and so on.

    Just some nitpicking: others already answered your question. Precision is important when dealing with technical issues and especially when asking technical answers. For this, in some cases it's better to express oneself in Perl rather than in English. In particular in Perl "foo boo doo" is a single string, so it may be slightly confusing. You can specify the contents of an array by... specifying the list of its contents, e.g. like thus:

    @question=('foo', 'boo', 'doo');

    If that seems like too much typing to you, then you can take advantage of the qw operator:

    @question=qw(foo boo doo);