Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-style loops vs Perl loops (in Perl)

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.

like image 459
Luke Avatar asked Dec 09 '22 08:12

Luke


2 Answers

$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.

like image 132
user2864740 Avatar answered Dec 10 '22 20:12

user2864740


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.)

like image 35
ikegami Avatar answered Dec 10 '22 21:12

ikegami