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

If a given array @array has in it an entry "entry", is there a way to find out where in the array it is?

Replies are listed 'Best First'.
Re: Array location?
by dragonchild (Archbishop) on Jul 08, 2003 at 19:17 UTC
    my $search = 'entry'; my @indices = grep { $array[$_] eq $search } 0 .. $#array;

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Array location?
by BrowserUk (Patriarch) on Jul 08, 2003 at 19:23 UTC

    A gazillion ways:). Here's one

    my $idx=0; $idx++ while $array[$idx] ne 'entry' and $idx < $#array; # Added! See [272470]. [cees]++ die 'Entry not found' if $idx == $#array and $array[-1] ne 'entry'; ## $array[$idx] is (the first!!) matching entry.

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


      You will get stuck in an endless loop with that one if the match is not in the array. I'm sure you meant:

      my $idx=0; $idx++ while $array[$idx] ne 'entry' && $idx < $#array; die 'Entry not found' if $idx == $#array and $array[-1] ne 'entry';

        cees++ Updated, thanks.

        Yes! I'm sure that's what I meant :)


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Re: Array location?
by derby (Abbot) on Jul 08, 2003 at 19:39 UTC
    And a gazillion plus one way:

    my @array = qw( you really don't know where the entry is do you ); my $cnt = 0; my %hash = map { $_ => $cnt++ } @array; print $hash{entry}, "\n";

    -derby

Re: Array location?
by shemp (Deacon) on Jul 08, 2003 at 19:18 UTC
    You can loop through all entries in the array and check each one to see if the value is "entry". What are you trying to do? It sounds like you may be better served using a hash.