Why no warning when redclaring a variable in same scope

Why no warning when redclaring a variable in same scope

am 21.09.2007 06:25:52 von Mintcake

#!/usr/local/bin/perl

use strict;
use warnings;

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

Re: Why no warning when redclaring a variable in same scope

am 21.09.2007 09:51:06 von Dummy

Mintcake wrote:
> #!/usr/local/bin/perl
>
> use strict;
> use warnings;
>
> for my $i (1..10)
> {
> my $i = 0; # Why no warning
> }

Different scope.


John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall

Re: Why no warning when redclaring a variable in same scope

am 21.09.2007 14:18:29 von Paul Lalli

On Sep 21, 12:25 am, Mintcake wrote:
> #!/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

Re: Why no warning when redclaring a variable in same scope

am 24.09.2007 02:36:25 von Mintcake

On Sep 21, 2:51 pm, "John W. Krahn" wrote:
> Mintcake wrote:
> > #!/usr/local/bin/perl
>
> > use strict;
> > use warnings;
>
> > for my $i (1..10)
> > {
> > my $i = 0; # Why no warning
> > }
>
> Different scope.
>
> John
> --
> Perl isn't a toolbox, but a small machine shop where you
> can special-order certain sorts of tools at low cost and
> in short order. -- Larry Wall

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

Re: Why no warning when redclaring a variable in same scope

am 24.09.2007 04:07:34 von Dummy

Mintcake wrote:
>
> On Sep 21, 2:51 pm, "John W. Krahn" wrote:
>>
>> Mintcake wrote:
>>>
>>> #!/usr/local/bin/perl
>>>
>>> use strict;
>>> use warnings;
>>>
>>> for my $i (1..10)
>>> {
>>> my $i = 0; # Why no warning
>>> }
>>
>> Different scope.
>
> 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
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall