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


In reply to Re: How to find the index of an element in an array? by holdyourhorses
in thread How to find the index of an element in an array? by knsridhar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.