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

Hi Monks

I have an array with the following elements. I want to get then index of element 'g' in the array. In this case its 6.

@foo=('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i');
How to get this?

CODE tags added by Arunbear

Replies are listed 'Best First'.
Re: How to find the index of an element in an array?
by holdyourhorses (Monk) on Sep 06, 2005 at 07:29 UTC

    Short answer: if you are going to need this calculation only once, use a loop. If you need to do this kind of calculation all the times, refactor your code.

    Here goes the longer explanation.

    A loop is the fastest way to get the index of an array item, if you need it only once. Getting that information from a hash is faster, but filling that hash is not going to be faster than a simple loop.

    LOOP: for (0 .. $#array) { if ($array[$_] eq $searched) { print "$searched found at $_ \n"; last LOOP; } }

    Notice that this approach would find the first occurrence of the item, therefore giving you that index. Conversely, using a hash would give you the last occurrence of the same item, unless you take it into account.

    For example, this will hold the last index of each item.

    my %hash; $hash{array[$_]} = $_ for 0 .. $#array;

    To get all the indices of each item, you should do this, instead:

    push @{ $hash{array[$_]} } , $_ for 0 .. $#array;

    Now, for the long array, the one that you can't afford to store into a hash, because it would more than double your memory occupation.

    If you are in such a situation, you can't build a hash, and looping through the array is going to take long as well. Therefore, you have to refactor your code, using a different data structure or removing the need for knowing the index of a given item. QED.

    HTH

Re: How to find the index of an element in an array?
by snoopy (Curate) on Sep 06, 2005 at 07:16 UTC
    List::MoreUtils is implemented in C and might give a modest performance advantage.
    #!/usr/bin/perl -w use List::MoreUtils; my @foo=('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i'); my $index = List::MoreUtils::first_index {$_ eq 'g'} @foo; print ("G's index = $index\n");
      There is also "indexes" if there may be more than one "g"
Re: How to find the index of an element in an array?
by holli (Abbot) on Sep 06, 2005 at 06:48 UTC
    @foo=('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'g'); @idx = grep { $foo[$_] eq 'g' } (0..$#foo); print "@idx"; #6 9


    holli, /regexed monk/
Re: How to find the index of an element in an array?
by planetscape (Chancellor) on Sep 06, 2005 at 10:24 UTC
Re: How to find the index of an element in an array?
by sk (Curate) on Sep 06, 2005 at 06:25 UTC
    I am not sure how big an array it is. But if it is small enough and also you want to find such indices all the time then you can try something like this by creating a hash whose value corresponds to the index

    #!/usr/bin/perl -w my @foo=('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i'); my %bar; my $i = 0; $bar{$_} = $i++ for (@foo); print ("G's index = $bar{'g'}\n"); __END__ G's index = 6
      Thanks a lot for your reply. Even i am not sure about how big my array would be as i am populating that array from an CSV file.

      Is there any other possible solution ??

      Edit g0n - removed 'pre' tags

        There are other ways.

        0. Making a hash out (my previous post)

        1. Loop through the elements and check for the value you are looking for and return the index. This is O(n) and very inefficient if you want to get the index quite frequently and if your array is big

        2. You had a,b,c etc. as elements then to find g then you can do something like binary search. This assumes your list/array is ordered.

        3. Come up with your own data structure.

        All these things are related to your original question but if you post your original problem then someone might be able to suggest you a better way to do it. Maybe there is a solution that does not require an index

Re: How to find the index of an element in an array?
by neversaint (Deacon) on Sep 06, 2005 at 06:52 UTC
    Dear Masters,
    Perhaps this is too banal, but TIMTOWTDI!
    perl -e ' @foo=('a','b','c', 'd', 'e', 'f', 'g', 'h', 'i'); $str = join("",@foo); $idx = index($str,'g'); print "$str-$idx\n";'
    prints:
    abcdefghi-6


    ---
    neversaint and everlastingly indebted.......
      This fails horribly when the array looks like
      @foo=('a', 'bb', 'ccc', 'dddd', 'e' x 50);


      holli, /regexed monk/
Re: How to find the index of an element in an array?
by jonhy (Initiate) on Sep 06, 2005 at 16:22 UTC
    try this code mate!!! my $a=0; my $b; foreach my $i (@foo){ if ($i eq 'g'){ $b=$a; } $a++; } $b will give you the index of element of 'g'