[Charlotte.PM] find index of array element

drewhead at drewhead.org drewhead at drewhead.org
Tue Mar 22 07:38:37 PST 2005

Hash: SHA1

> my @array = qw( item1 item2 item3 item4 );

> find the index of item3. 

The knock on grep is that it is pretty much looping though every element,
like map would, which essientailly makes them the same as a foreach loop.
Those things don't tend to scale well.

Why do you need to know an array index? Can you control the structure of the array?
If so makeing this a hash when you build the data structure where your
keys are the element values of the array and the hash key value would be a
count scalar incremented with each assignment.  Then you could get the
index, or more appropriately stated the ordinal position of an element at
assignment, simply by refrencing it's hash value.

my %hash = { 
    'item1' => 1,
    'item2' => 2,
    'item3' => 3,
    'item4' => 4,

my $index = $hash{'item3'};

This assumes your array elements are unique.

I know this isn't really what you asked, but depending on your application
it and how many times you need to lookup an index value it may be worth it
to build this structure even if you don't have control of the array

I find I only use arrays when I know I'm never going to care about the
index of the elements and I know I'll never have need to look up a specfic
value.  Otherwise I type % without even thinking about it.  :)

- -- 
     Drew Dowling               Drewhead          http://www.drewhead.org
 drewhead at drewhead.org    |                    |    WWW      / \ Alpha Phi Omega
Concord, North Carolina   |                    |  Nimat     /   \  Gamma Lambda
CLEMSON UNIVERSITY ALUMNI |                    | Apatschin /_____\
      TIGER BAND!         |      VGAP4 Hosting at http://vgap.drewhead.org
Comment: Public key available at http://www.drewhead.org


More information about the charlotte mailing list