What I won’t get about foreach loops?

I always understood that

foreach (@arr)
{
    ....
}

and

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

were functionally equivalent. However, in all my code, whenever I use a loop foreach, I run into problems that get fixed when the loop changes for. This is always associated with comparing the values ​​of two things, usually with nested loops.

Here is an example:

for(my $i=0; $i<@files; $i++)
{
    my $sel;
    foreach (@selected)
    {
        if(files[$i] eq selected[$_])
        {
            $selected='selected';
        }
    }
    <option value=$Files[$i] $sel>$files[$i]</option>
}

The above code falls between the select tags in the cgi program. I mainly edit the contents of the selection window according to user specifications. But after adding or removing options, I want the choices that were initially selected to remain selected.

. foreach , . 3 for, , .

, - , - ?

+2
1

, @files - .

$i - (.. ):

for (my $i=0; $i<@files; $i++) { ... }

$i (.. ):

foreach my $i (@files) { ... }

, :

use strict;
use warnings;

my @files = (
   'foo.txt',
   'bar.txt',
   'baz.txt',
);

print "for...\n";
for (my $i=0; $i<@files; $i++) {
   print "\$i is $i.\n";
}

print "foreach...\n";
foreach my $i (@files) {
   print "\$i is $i.\n";
}

:

for...
$i is 0.
$i is 1.
$i is 2.
foreach...
$i is foo.txt.
$i is bar.txt.
$i is baz.txt.

foreach, , , " ", , for (my $i=1;...;...) for (my $i=0;$i<=@arr;...).

, for foreach Perl, script :

use strict;
use warnings;

my @files = (
   'foo.txt',
   'bar.txt',
   'baz.txt',
);

print "for...\n";
foreach (my $i=0; $i<@files; $i++) {
   print "\$i is $i.\n";
}

print "foreach...\n";
for my $i (@files) {
   print "\$i is $i.\n";
}

foreach, for ( ).

+4

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


All Articles