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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return Position of Element in an Array

Status
Not open for further replies.

aj2taylo

Programmer
Nov 4, 2002
17
CA
Suppose I have an array @list, and I want to know where "foo" is in the list. Is there a short command to return that "foo" is the nth element of the array?
 
@test= ("a","b","c","d", "foo", "e", "f", "g", "h");

foreach $var (0 .. $#test) {
if ($test[$var] eq 'foo') { print $var; }
}
 
if you expect "foo" to be in the list once you may want to also use "last" to end the loop early:

Code:
my $found = 0;
for my $i (0 .. $#array) {
   if ($array[$i] eq 'foo') {
      print "'foo' found at position: $i\n";
      $found++;
      last;
   }
}
print "'foo' not found\n" unless ($found);
 
My first thought was this:
Code:
@test=qw(a b c d foo e f g h);
for (0 .. $#test) {print && last if($test[$_] eq "foo")};
Reasonably concise.

My next thought was that if you're gonna do lots of this on that data then maybe you'd be better creating a hash where the keys are your array values and the hash values are the indexes into the array.



Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top