C-style cycles against Perl feathers (in Perl)

I feel that there is something that I cannot get about the perl loop mechanism.

I realized that

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

was functionally equivalent to:

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

However, in my code there are apparently some slight differences in how they work. in particular, the time during which they decide when to terminate. eg:

Suppose that @arr is initialized with a single variable.

Should these two blocks 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);
    } 
} 

However, when executed, despite the fact that in both cases a new value will be added, the first loop will stop only after one iteration.

Is this supposed to be? if so, why?

: . , . , , . , . , , c. , , c, .

+4
3

$i<=$#arr , (0 .. $#arr) .

, "" @arr.

+9

, , ? ( c-)

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

-

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

( $i .)

+3

An alternative would be a do-while construct, although this is a bit inconvenient.

my $i;
do {
    push @arr, $value if condition;
} while ( $i++ < @arr );
+2
source

Source: https://habr.com/ru/post/1538460/


All Articles