SPUG: Confusing behaivior with exported variables

Ronald J Kimball rjk-spug at tamias.net
Tue Mar 24 13:37:33 PDT 2009


On Tue, Mar 24, 2009 at 12:25:39PM -0700, Mark Mertel wrote:
>
> It does work:
>
> package Foo;
> my $bar = "foo bar\n";
> 1;
> ...
>
> use Foo;
> use strict;
>
> print $Foo::bar; # prints 'foo bar'
>
> print $bar; # should throw an error

Did you actually execute this code?  It /does not/ do what you say it does.

It would be a very good idea for you to take the time to understand how
my()/our() and lexical/package variables actually work before you spread
more misinformation on this subject.

Variables declared with my() are lexically scoped.  They are not stored in
the symbol table.  They are accessible only from within that lexical scope.

Variables declared with our() are package variables.  They are stored in
the symbol table.  They are accessible globally, but may need to be fully
qualified.

package Foo;
use strict;

{
  my $foo = 'foo';   # sets lexical $foo

  print "$foo\n";    # prints 'foo'
}

#print "$foo\n";     # error under use strict, prints undef otherwise

{
  my $foo;           # a different lexical $foo
  print "$foo\n";    # prints undef
}

{
  our $bar = 'bar';  # sets $Foo::bar
  print "$bar\n";    # prints 'bar'
}

#print "$bar\n";     # error under use strict, prints 'bar' otherwise
print "$Foo::bar\n"; # prints 'bar'

{
  our $bar;          # same $Foo::bar
  print "$bar\n";    # prints 'bar'
}

Ronald


More information about the spug-list mailing list