Finding what number an item is in an array.

They have: 62 posts

Joined: May 2000

OK, let's say I have the constant "Lalala". Then I have the ever change array (like a file). Is it possible for me to find out where in that array the string "Lalala" is located? Such as item number 12.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

probably a better way, but this should work.

$SearchString = "Lalala";

$counter = "0";
foreach @YourArray {
unless ($_ == $SearchString) {
$counter++;
}
}

print qq~"$SearchString"  is number $counter in YourArray.~;
'

Mark Hensler
If there is no answer on Google, then there is no question.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

OOOOPPSII!!!

forgot to tell it to exit the foreach!!

$SearchString = "Lalala";

$counter = "0";
foreach @YourArray {
if ($_ == $SearchString) {$exit = "y";}
if ($exit != "y") {$counter++;}
}

print qq~"$SearchString"  is number $counter in YourArray.~;
'

Mark Hensler
If there is no answer on Google, then there is no question.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.