Get the index of array element

R

ravi

In the following piece of code

foreach $element (@array) {

# Is there a special variable to know the index
# of the array element

}

Is there a efficient way to know the index of the array element inside
the given loop, assuming i dont have a count variable.
 
A

Anno Siegel

ravi said:
In the following piece of code

foreach $element (@array) {

# Is there a special variable to know the index
# of the array element
No.

}

Is there a efficient way to know the index of the array element inside
the given loop, assuming i dont have a count variable.

You'll need an index variable in one form or another. The basic
possibilities are either

my $i = 0;
foreach $element ( @array ) {
# index in $i
$i ++;
}

or

for ( 0 .. $#array ) {
my $element = $array[ $_];
# index in $_
}

Anno
 
B

Bart Lateur

Anno said:
my $i = 0;
foreach $element ( @array ) {
# index in $i
$i ++;
}

If I use that kind of code structure, I always put the last statement in
a "continue" block, even if it doesn't sever any other particular
practical purpose.

my $i = 0;
foreach $element ( @array ) {
# index in $i
} continue {
$i ++;
}

At least it'll behave properly if even if at one point you choose to
insert a "next" statement in there.
 
A

Anno Siegel

Bart Lateur said:
If I use that kind of code structure, I always put the last statement in
a "continue" block, even if it doesn't sever any other particular
practical purpose.

On the contrary! "next" would sever the increment from control flow
if it were otherwise :)
my $i = 0;
foreach $element ( @array ) {
# index in $i
} continue {
$i ++;
}

At least it'll behave properly if even if at one point you choose to
insert a "next" statement in there.

Either that, or arrange things so that the increment is the first thing
in the loop. Sometimes it's "my $i = -1;" for that reason.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top