in reply to How is it that I can see this package variable from another package without fully-qualifying its name?

An our (see especially the first paragraph) binding respects scope—in this case, file scope.

  • Comment on Re: How is it that I can see this package variable from another package without fully-qualifying its name?

Replies are listed 'Best First'.
Re^2: How is it that I can see this package variable from another package without fully-qualifying its name?
by Anonymous Monk on Apr 24, 2011 at 19:53 UTC

    I don't know exactly what you mean when you say that an our binding "respects scope".

    I do see that the declaration and definition of $var is at file scope. My understanding is that "package Bar" changes the package from Foo to Bar. Maybe I'm confusing "change of package" with "change of scope"?

    I see that the following works as I'd expect:

    #!/usr/bin/env perl use Modern::Perl; { package Foo; our $var = 42; # This is $Foo::var. } { package Bar; # This works, as expected. say "\$Foo::var: $Foo::var"; #say "\$var: $var"; # Fails, as expected. } #say "\$var: $var"; # Fails, as expected. say "\$Foo::var: $Foo::var";

    Does that look like the correct way to keep packages separate in a single file?

    (I realize that everything would also work as expected if I kept each package in its own module. And it would make them easily testable as well.)

      Maybe I'm confusing "change of package" with "change of scope"?

      Exactly! The package keyword doesn't introduce a new scope for my or our bindings. Only a new file or curly braces do.

      Keeping each package in a separate file is generally the best approach, but using curly braces to isolate packages works well too. Perl 5.14 has a new package NAME { ... } syntax to make this even easier.