> -----Original Message-----
> From: Richard Adams [mailto:[EMAIL PROTECTED]]
> Sent: Tuesday, June 04, 2002 6:13 AM
> To: [EMAIL PROTECTED]
> Subject: Use of our
> 
> 
> Hi,
> I'm sure this has been asked before, but I'm having a problem with
> understanding "our".
> 
> I get the idea  of my, and also variable declared without a 
> qualifier is
> visible to all packages/modules..also that $package::varname 
> can be used to
> access a global variable in another package...
> 
> But the more I read the camel book the more confused I get, 
> especially about
> the lexical scoping of our..if it's lexically scoped how can 
> it be global??

There are two concepts involved: "scope" and "lifetime". The
term "lexical", which refers to the structure of the source
code, can be applied to both.

"my" creates variables with a lexical lifetime. That is, the
variable only "exists" from the point of declaration, until the
end of the innermost enclosing eval, block, or file. Outside of
that scope, the variable is not accessible.

"our", on the other hand, deals only with global (i.e. package)
variables. These variables have a global lifetime, i.e. they
exist for the total lifetime of the program execution. "our"
does not create anything.

So what does "our" do? It simply declares that a global variable
can be used without a package qualifier. The "scope" in which you
can use this variable without a package qualifier is lexical; i.e.
you can use the variable without a package qualifier anywhere
from the "our" declaration to the end of the innermost eval, block,
or file. Outside of that scope, you need a package qualifier on
the variable.

Now by default, Perl allows you to refer to global variables without
a package qualifier anyway, unless you "use strict". So "our" has no
real effect unless "use strict" is in force (n.b. beginners: you
should A-L-W-A-Y-S "use strict" in your programs).

Prior to Perl 5.6, the "use vars" pragma was the way to accomplish
this same thing. "use vars" has slightly different scoping, so be
sure to:

   perldoc -f our
   perldoc vars

> Does declaring  "our $a" refer to a previously declared $a in another
> package/module,

No, not previously declared, but simply an ordinary global variable.

> with the lexical scoping keeping it within a 
> block of the
> current package?

No, see above.

> 
> Any help in clearing the fog from my brain greatly appreciated...

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to