my $var; doesn't do anything to the symbol table. It creates a lexical variable in a sort of lexical pad. A lexical variable is created, lexically scoped, and completely independent of the package symbol table.
our $var; creates an entry in the symbol table. our does create an entry in the symbol table. our follows scoping rules similar to my, but the variable created is a package global.
Try this:
package main; use strict; use warnings; my $lexical = 100; our $global = 200; print $main::global, "\n"; print $main::lexical, "\n";
The output shows that "my $lexical" never created an entry in the global symbol table.
It's not wierd that you can declare an our variable and a my variable at the same time, because they're two different variables. It's true that one can mask the other if you're not using "fully qualified" names. But nevertheless, the two variables to exist.
Try the following example where two variables by the same name are created:
package main; use strict; use warnings; our $var = 200; my $var = 100; print $var, "\n"; print $main::var, "\n";
Now it will print 100 then 200 (and some warnings). This shows that even though the my declaration "masks" the our declaration, you can still get at the global by using its fully qualified name. If you had declared the lexical first and then the 'our' variable, the lexical becomes masked, and since there's no such thing as a "fully qualified" lexical name, you can't get at it anymore, until the 'our' variable passes out of scope (which in the case of my example isn't possible, but it is possible to construct such a situation pretty easily).
References also help to illustrate what's going on. Watch this:
package main; use strict; use warnings; my $var = 100; my $ref_to_lexical = \$var; our $var = 200; my $ref_to_global = \$var; print $var, "\n"; # This prints 200. The lexical is masked. print $$ref_to_global, "\n"; # This prints 200. print $$ref_to_lexical, "\n" # This prints 100, it refers to # the lexical $var.
Clear as mud? :)
Dave
In reply to Re: OUR declaration
by davido
in thread OUR declaration
by Anonymous Monk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |