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

Index of current array

Status
Not open for further replies.

zzzqqq

Programmer
Oct 12, 2005
17
IE
Hi,
Anyone know is it possible to get the current index of an array in perl?
Eg. $index = @array($index);
Say current index is 3.
Cheers,
Mark.
 
I don't understand your question and I'm not sure you do either!
Your syntax is incorrect for accessing an element via an index.
If you can try to explain in a little more detail what exactly you are trying to do I'm sure we can help.



Trojan.
 
Cheers,
Just trying to find the index number of an element in an array. say $array[3] = "29".
Hoping there's a way of finding the index number, i.e. say the 3 number in this case.
Mark.
 
I guess you are looking d=for the position...

e.g

@list=("Monday","Tuesday","Wednesday","Thursday","Friday");
$look_for="Wednesday";

for ($i=0; $i<$#list; $i++) {
if ($list[$i] eq $look_for) { last; }
}

print "The word $look_for is item number $i in the list";


dmazzini
GSM System and Telecomm Consultant

 
Then you need to search the array in sequence.
Or you need to create a hash of values to use for lookup.

Try this:

Code:
my $index =  undef;
for(my $i=0; $i<=$#array; $i++) {
  $index = $i if($array[$i] == 3);
}
print $index,"\n" if(defined $index);



Trojan.
 
Code:
my @array=qw/1 2 3 4 5 6 7 8 9 10/;
print "\@array starts at \$array[0] and ends at \$array[";
print $#array , "]\n";
 
Just trying to find the index number of an element in an array. say $array[3] = "29".

well, if you know $array[3] = 29 you already have the index number, which is 3, the 4th element of the array.
 
Yeah. Perl arrays are 0-indexed and $#arrayname is the index to the last element of the array, one less than the total number of elements in the array.

pop(@array) returns the last element of @array (and removes it from the array decreasing its length)
shift(@array) returns the first (0-indexed) element of @array (removing it from the @array and decreasing $#array by one)

Both pop and shift can return undefined if the array is empty. Both default to @ARGV or @_ if not given an array depending on what scope your program happens to be in at that point. =)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top