Why no warning when redclaring a variable in same scope

M

Mintcake

#!/usr/local/bin/perl

use strict;
use warnings;

for my $i (1..10)
{
my $i = 0; # Why no warning
}
 
P

Paul Lalli

#!/usr/local/bin/perl

use strict;
use warnings;

for my $i (1..10)
{
my $i = 0; # Why no warning

It's not the same scope. It's a subset of the other scope. The first
$i's scope is for the entire loop, ncluding the loop header - the list
of 1..10. The second $i's scope is only for the body of the loop,
not for its header.

{
my $i;
my $i; # Warning!
{
my $i; # No warning!
}
}

Paul Lalli
 
J

John W. Krahn

Mintcake said:
Why different scope? - both instances of $i exist only with the {}

The braces {} define scope (within a file) except (Perl has a lot of
exceptions :) for the variable declared for a foreach loop which has "special"
scope.

$ perl -wle'
for my $i ( 0 .. 9 ) {
print __LINE__, ": $i";
my $i = 20;
print __LINE__, ": $i";
}
continue {
print __LINE__, ": $i";
}
print __LINE__, ": $i";
'
Name "main::i" used only once: possible typo at -e line 10.
3: 0
5: 20
8: 0
3: 1
5: 20
8: 1
3: 2
5: 20
8: 2
3: 3
5: 20
8: 3
3: 4
5: 20
8: 4
3: 5
5: 20
8: 5
3: 6
5: 20
8: 6
3: 7
5: 20
8: 7
3: 8
5: 20
8: 8
3: 9
5: 20
8: 9
Use of uninitialized value in concatenation (.) or string at -e line 10.
10:



John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top