Reconfiguring the Perl foreach loop variable

I am new to perl and am confused with the rules for defining perl after writing the code snippet below:

#!/usr/bin/perl
my $i = 0;
foreach $i(5..10){
    print $i."\n";
}
print "Outside loop i = $i\n";

I expected the output to be like this:

5
6
7
8
9
10
Outside loop i = 10

But its provision:

5
6
7
8
9
10
Outside loop i = 0

Thus, the value of the variable $ i does not change after the loop exits. What's going on here?

+4
source share
3 answers

According to perldoc information regarding foreach loops: here

foreach VAR . my, . . ​​ my, , . foreach.

$i , $i foreach perl $_ :

#!/usr/bin/perl

use strict;
use warnings;

my $i = 0;
foreach (5..10){
    print $_."\n";
    $i = $_;
}
print "Outside loop i = $i\n";

5 6 7 8 9 10 = 10

+5

foreach .

use strict;
use warnings;

my $adr;
my $i = 0;
foreach $i(5..10){
    $adr = \$i;
    print "$i ($adr)\n";
}
$adr = \$i;
print "Outside loop i = $i ($adr)\n";

5 (SCALAR(0x9d1e1d8))
6 (SCALAR(0x9d1e1d8))
7 (SCALAR(0x9d1e1d8))
8 (SCALAR(0x9d1e1d8))
9 (SCALAR(0x9d1e1d8))
10 (SCALAR(0x9d1e1d8))
Outside loop i = 0 (SCALAR(0x9d343a0))

perldoc,

foreach VAR . my, , , . . ​​ my, , , . foreach.

$i, C for,

my $i = 0;
for ($i = 5; $i <= 10; $i++) { .. }

, perl foreach

+4

$i foreach

foreach $i(5..10){

Thus, a variable outside the foreach will not change.

0
source

All Articles