LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Perl and nested loop substitution (https://www.linuxquestions.org/questions/linux-general-1/perl-and-nested-loop-substitution-804710/)

Evgeniy Arbatov 04-28-2010 04:32 AM

Perl and nested loop substitution
 
Hello! I have a trouble with getting Perl to substitute a regular expression in a nested loop. The construction is like this:

Code:

for ($i=11; $i<=99; $i++) {
        foreach my $line (@input) {
                if ($line =~ /10/) {
                        $line =~ s/10/$i/;
                        print $line . "\n";
                }
        }
}

However, the $i inside the foreach loop does not increment at the same time as $i in the for loop does. In fact, $i in the inner loop stays 11 until the for loop exits.

Please tell me, why this is the case? Many thanks.

Evgeniy

smoker 04-28-2010 05:05 AM

Your inner loop substitutes 11 for every 10 found in @input
So the next time the outer loop runs, and increments i, all the matches and substitutions have already been done,

There will never be a 10 to match in the inner loop after the first run. The if statement is never true. The printed i is always 11.

example containing 3 x 10, and showing the array after each pass of the inner loop.
Code:

#!/usr/bin/perl


@input = qw(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 10 98 15 13 10);

print "@input\n";

for ($i=11; $i<=20; $i++) {
        foreach my $line (@input) {
                if ($line =~ /10/) {
                        $line =~ s/10/$i/;
                        print $line . "\n";
                }
        }
        print "iteration $i : @input\n";
}

Gives the output :

Code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 10 98 15 13 10
11
11
11
iteration 11 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 12 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 13 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 14 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 15 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 16 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 17 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 18 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 19 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11
iteration 20 : 1 2 3 4 5 6 7 8 9 11 11 12 13 14 15 16 17 18 19 20 11 98 15 13 11


Evgeniy Arbatov 04-28-2010 05:19 AM

Thanks a lot! I have confused myself


All times are GMT -5. The time now is 09:37 AM.