Re: Does "my" vs "our" explain this problem?
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 8 Feb 2006 08:28:07 -0800
CedricCicada@xxxxxxxxx wrote:
Greetings!
I have a script that calls a module. In the script, I define a global
variable using "my" and assign it a value.
That is a contradiction in terms. 'my' variables, by definition, are
not global. They are lexically scoped to the innermost block in which
they were declared. If there is no block, they are file-scoped.
In the module, I use
$main::myGlobal to read the global variable, and I find that it is
empty. Should I define the global variable using "our" instead?
'our' is the only way to "declare" a global variable*. You did not
have a global variable. You had a lexical variable.
Google for "Coping with Scoping."
mymoduletest.pl:
use MyModule;
my $myGlobal = "This is a global variable.";
No, it's not. It's a lexical variable, who's scope happens to be the
entire scope of the file mymoduletest.pl. Anywhere outside that file,
that variable does not exist.
MyModule::myMethod();
MyModule.pm:
sub myMethod()
{
print "Global variable contains $main::myGlobal\n";
This is the global variable $myGlobal that belongs to the package main.
}
This is, in general, really bad form. Your packages should not have
any access to the package 'main' without very good reason (and I can't
think of any good reasons right now). While it makes more sense for
package main to have access to your module's variables, it's still bad
form - declare all variables lexically, and right accessor subroutines
and methods.
Paul Lalli
* 'our' doesn't actually "declare" global variables, because global
variables are not declared, they simply exist. 'our' simply allows you
to use that global variable without fully qualifying it (ie, preceding
it with its package's name) even though strict vars is in scope, for
the duration of the lexical scope. Anywhere outside the 'our''s scope,
you still have to fully qualify the variable if strict is in effect.
.
- Follow-Ups:
- Re: Does "my" vs "our" explain this problem?
- From: Rob Richardson
- Re: Does "my" vs "our" explain this problem?
- From: Rob Richardson
- Re: Does "my" vs "our" explain this problem?
- References:
- Does "my" vs "our" explain this problem?
- From: CedricCicada
- Does "my" vs "our" explain this problem?
- Prev by Date: Does "my" vs "our" explain this problem?
- Next by Date: Re: Does "my" vs "our" explain this problem?
- Previous by thread: Does "my" vs "our" explain this problem?
- Next by thread: Re: Does "my" vs "our" explain this problem?
- Index(es):
Relevant Pages
|