dsb has asked for the wisdom of the Perl Monks concerning the following question:
An "our" declares the listed variables to be valid globals within the enclosing block, file, or "eval". That is, it has the same scoping rules as a "my" declaration, but does not create a local variable.
...
An "our" declaration declares a global variable that will be visible across its entire lexical scope, even across package boundaries. The package in which the variable is entered is determined at the point of the declaration, not at the point of use.
Given that explanation, I would've thought you could use our() to localize a variable. If our() has the same scoping rules as my(), then I would've thought that the following two snippets result the same.
and$var = 1; { my $var = 2; print $var, "\n"; # prints 2 } print $var, "\n"; # prints 1
But they don't, and I can't understand why. I'm guessing that it has something to do with the fact the second our() declaration clobbers the first, but that assumption seems to ignore the scoping rules that the docs say are the same as my().our $var = 1; { our $var = 2; print $var, "\n"; # prints 2 } print $var, "\n"; # also prints 2
Anyone?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: my() and our()
by merlyn (Sage) on Aug 09, 2005 at 14:40 UTC | |
|
Re: my() and our()
by bunnyman (Hermit) on Aug 09, 2005 at 15:25 UTC | |
by DrWhy (Chaplain) on Aug 09, 2005 at 22:08 UTC | |
|
Re: my() and our()
by Joost (Canon) on Aug 09, 2005 at 15:19 UTC | |
|
Re: my() and our()
by emazep (Priest) on Aug 09, 2005 at 16:28 UTC | |
|
Re: my() and our()
by revdiablo (Prior) on Aug 09, 2005 at 15:49 UTC | |
|
Re: my() and our()
by xdg (Monsignor) on Aug 09, 2005 at 18:48 UTC |