in reply to How to find the index of an element in an array?

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

Replies are listed 'Best First'.
Re^2: How to find the index of an element in an array?
by knsridhar (Scribe) on Sep 06, 2005 at 06:35 UTC
    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