[oak perl] still clueless about "my"

Steve Fink sfink at reactrix.com
Fri Feb 4 10:01:50 PST 2005


Sandy Santra wrote:
 >>  foreach my $file ( glob '*' ) {
 >>      my $newfile = $file ;
 >>  }
 >
 >
 > because you put the "my" definition within the If statement.

A 'my' used with a 'for' or 'foreach' is a little bit of an exception to 
the a-scope-is-enclosed-in-curly-brackets rule.

  use strict;
  for my $x (1..2) {
    print "x=$x\n";
  }
  print $x;

is a syntax error because 'for my $...' actually puts the scope of the 
variable within the for loop's curlies. (This isn't just 'for'; do 
'perldoc perlsub' and read the "Private Variables via my()" section for 
the full details.)

And it's worse than that. If you "fix" the above example by saying

  use strict;
  my $x;
  for $x (1..2) {
    print "x=$x\n";
  }
  print "x is now $x\n";

then in terms of scoping, everything is correct. But (I'm just 
mentioning this because it's easy to encounter while you're trying out 
examples) it will print

  x=1
  x=2
  x is now

That last line will give a "Use of uninitialized value" warning if you 
run with warnings on. This actually doesn't have that much to do with 
scoping. It's another magical thing about 'for/foreach'. They implicitly 
do a 'local $x' on their $x iterator variable. So even though you're 
talking about the same my'd $x inside and outside the for, the value is 
reset to what it was before the 'for'. Try this:

  use strict;
  my $x = 'smurf hair';
  for $x (1..2) {
    print "x=$x\n";
  }
  print "x is now $x\n";

 > Alright, I'm going to eat some worms now.

The red wiggly ones have a stronger taste but more nutrition. I would 
recommend sticking to nightcrawlers when you're not completely confused, 
and only go for a handful of those red guys if you get entirely lost.


More information about the Oakland mailing list