in reply to Re: Using an "outer" lexical in a sub?
in thread Using an "outer" lexical in a sub?

#!/usr/bin/perl use strict; use warnings; # "our $n;" disables "use strict 'vars';" for $n for the # remainder of the lexical scope in which it is located. sub foo { our $n; $n++; } our $n = 10; print "$n\n"; # 10 foo(); print "$n\n"; # 11

Well, this example helps me somewhat (though seemingly (to me) not directly with what I was originally confused about). Thank you. I'd previously always written "our $n = $whatever;" assuming that it atomically meant, "create a package global named $n with $whatever value". Looking more closely at our though, I see that that statement is really doing *2* separate things:

  1. Letting me refer to $main::n as just plain $n.
  2. Setting $n to something ($n springs into existence at *this* point).

(Should've read the docs on our more carefully -- they're very good.)

So, in your example above, I now see that "our $n;" in sub foo isn't defining anything -- just telling perl that I'll be referring to $main::n in here as "$n". :)

Replies are listed 'Best First'.
Re^3: Using an "outer" lexical in a sub?
by ikegami (Patriarch) on Nov 01, 2006 at 21:42 UTC
    Pragmas (such as use strict), my variables, our declerations (but not package variables), package statements, etc all have lexical scope. A lexical scope spans (includes) its child lexical scope.
    use strict; sub f { # strict still in effect in this child block if (...) { # strict still in effect in this child block for (...) { # strict still in effect in this child block { # strict still in effect in this child block } } } }
    my $n; sub f { # $n is still accessible in this child block if (...) { # $n is still accessible in this child block for (...) { # $n is still accessible in this child block { # $n is still accessible in this child block } } } }
    { use strict; # strict still in effect } # strict no longer in effect
    { my $n; # $n accessible. } # $n no longer accessible.
Re^3: Using an "outer" lexical in a sub?
by Joost (Canon) on Nov 01, 2006 at 21:00 UTC
      Some of us have figured out that it is better to use vars in modern days as well. And if you're going to use our, then use it in the biggest possible scope.

      Seriously, in my eyes our is a language misfeature. My understanding is that it was introduced as a hook upon which further features can be hung. In Perl 6 those features will be hung upon it and it makes more sense. But in Perl 5 it is worse than what it replaced.

      However it is great for surprising the maintainer. For instance:

      package Foo; our $_ = "gotcha"; for (1, 2, 3) { print; print ": $_\n"; }