Question

I feel like there is something I don't get about perl's looping mechanism.

It was my understanding that

for my $j (0 .. $#arr){...} 

was functionally equivalent to:

for(my $i=0; $i<=$#arr; $i++){..}

However, in my code there seems to be some slight differences in the way they operate. specifically, the time in which they decide when to terminate. for example:

assume @arr is initialized with one variable in it.

These two blocks should do the same thing right?

for my $i (0 .. $#arr)
{
    if(some condition that happens to be true)
    {
        push(@arr, $value);
    } 
} 

and

for (my $i=0; $i<=$#arr; $i++)
{
    if(some condition that happens to be true)
    {
        push(@arr, $value);
    } 
} 

In execution however, even though a new value gets pushed in both cases, the first loop will stop after only one iteration.

Is this supposed to happen? if so why?

EDIT: Thank you for all of your answers, I am aware I can accomplish the same thing with other looping mechanisms. when I asked if there was a another syntax, I was specifically talking about using for. Obviously there isn't. as the syntax to do what I want is already achieved with the c style. I was only asking because I was told to avoid the c style but i still like my for loops.

Was it helpful?

Solution

$i<=$#arr is evaluated before each loop while (0 .. $#arr) is evaluated once before any loop.

As such, the first code doesn't "see" the changes to the @arr size.

OTHER TIPS

Is there another syntax I can use that would force the evaluation after each iteration? (besides using c-style)

for (my $i=0; $i<=$#arr; $i++) {
   ...
}

is just another way of writing

my $i=0;
while ($i<=$#arr) {
   ...
} continue {
   $i++;
}

(Except the scope of $i is slightly different.)

An alternative would be the do-while construct, although it is a little ungainly.

my $i;
do {
    push @arr, $value if condition;
} while ( $i++ < @arr );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top