Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How Do I Find the position of a value in an array?

Status
Not open for further replies.

soy4soy

IS-IT--Management
May 22, 2000
100
US
Happy Monday! I can't believe I am having this problem, but then it IS Monday.

There is a function, index(), that performs what I need without a for-if combo, but this works for strings.

I need an index() function for an array:

my @array = ( 'Blue', 'Red', 'Green', 'Yellow' );

#I want to know what will return the Position of 'Red' in @array:

my $element_position = array_index('Red');

#in other words, what would set $element_postition to 1?

Randy Mitchell, Jack of all ITrades
 
Here's one way, but since it's possible to have more than one item in an array with the same value, it returns a list of indecies.
Code:
$item = 'red';
@list = qw/blue red green yellow red/;
@indexes = grep $item eq $list[$_], 0..@list;
If your @list is huge, then 0..@list will make a huge array, too, and isn't overly memory friendly, but I doubt it's a problem. There's always more than one way to do it, this was the closest to a single "function" I could think of.

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Another wacky way to handle it would be to parse the array into a hash, each hash entry has its 'element position' as a value and can display it on command.

Just as memory hungry I suppose but a quick reference that can be used over and over again during the programs run cycle for the cost of one parse.

If you are hand constructing the 'array' then just hand construct the hash:

%list = (
'blue'=>'1',
'red'=>'2',
'green'=>'3',
'yellow'=>'4',
'red'=>'5'
);
$item = "red" ;
print $list{ $item } ;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top