confused a little by use strict

D

dan

Howdy,

The code:

use strict;

my $foo = 0;

for $foo (0,1) {
print "$foo\n";
}

print "$foo\n";

outputs

0
1
0

So $foo comes out of the loop unchanged. OK, if thats how it works, then
why complain if I write

use strict;

my $foo = 0;

for $mistake (0,1) {
print "$foo\n";
}

print "$foo\n";

which outputs
Global symbol "$mistake" requires explicit package name ...?

Since it complains, this implies that in the first case, $foo would come
out of the loop with value 1, doesn't it?
 
G

Gunnar Hjalmarsson

dan said:
The code:

use strict;
my $foo = 0;
for $foo (0,1) {
print "$foo\n";
}
print "$foo\n";

outputs

0
1
0

So $foo comes out of the loop unchanged.

The docs refer to it as "implicit localisation". Please read about
foreach loops in "perldoc perlsyn".
 
P

Peter Scott

use strict;

my $foo = 0;

for $foo (0,1) {
print "$foo\n";
}

print "$foo\n";

outputs

0
1
0

So $foo comes out of the loop unchanged. OK, if thats how it works, then
why complain if I write

use strict;

my $foo = 0;

for $mistake (0,1) {
print "$foo\n";
}

print "$foo\n";

which outputs
Global symbol "$mistake" requires explicit package name ...?

Since it complains, this implies that in the first case, $foo would come
out of the loop with value 1, doesn't it?

Your contention appears to be that since perl uses a 'temporary' variable
for the foreach iterator, shouldn't 'use strict' give it a pass if it's
not declared? The foreach semantics have evolved over the years and the
counterclaims to your argument are not as strong as they once were, but
nevertheless, at this point, perl elects to prefer to be consistent with
the "fully specify (or 'use vars') all package variables when using
strict" rule. Notice that if we turn strict off, we can see that perl
uses the package variable for the iterator if there's no lexical of the
same name (rather thab creating a new lexical):

$::foo = 'package';
for $foo ( 42 ) {
print "Package = $::foo\n";
}

# Package = 42

Just always say "for my ..." and you won't be bothered by these issues.
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top