I am new to perl and was confused with perl scoping rules after I wrote below code snippet:
#!/usr/bin/perl
my $i = 0;
foreach $i(5..10){
print $i."\n";
}
print "Outside loop i = $i\n";
I expected output to be like :
5
6
7
8
9
10
Outside loop i = 10
But its giving :
5
6
7
8
9
10
Outside loop i = 0
So the variable $i value is not changing after the loop exits. Whats going on in here?
According to the perldoc information regarding foreach loops: here
If you want to retain the value of $i outside the loop then you can omit $i in the foreach loop call and use perl's special variable $_ an example below:
5 6 7 8 9 10 Outside loop i = 10
The variable
$i
is redefined in foreach scope atSo the variable outside foreach will not change.
foreach
localize variable to the loop.output
From perldoc,
To preserve value of
$i
you can useC
likefor
loop,although it's less readable than perl
foreach