[Wellington-pm] 'my' and 'our'

Cliff Pratt enkidu at cliffp.com
Wed May 3 13:00:02 PDT 2006

Jacinta Richardson wrote:
> my is for lexical variables.  That is variables that exist and can only be seen
> in their current scope.  A variable's scope is defined as the smallest enclosing
> block (including file).
> our is for package variables (think globals).  These are variables that exist
> and can be accessed outside of the scope in which they were declared, for
> example in different files.
> Consider this example:
> ----------------------
> package Foo;
> my $bar;
> our $baz;
> {    # open new scope
>      my $gatx;
>      print $gatx;    # works
> }
> print $gatx;         # doesn't work (error)
> ----------------------
> # main program
> use Foo;
> print $Foo::baz;    # works
> print $Foo::bar;    # error, $bar can't be seen out here.
> -----------------------
> our replaces the need for "use vars" from code prior to 5.6.  It's a tiny bit
> more complicated than this, but not so much that it matters.
Thanks Jacinta.

So, if the variable ($bar) is not used outside the package, it can be 
declared with 'my'. If it is defined with 'our' it is available anywhere 
in the package (or scope) as simply $bar, but outside the package (or 
scope) it is available as $Foo::bar, then?

Since all object variables should be accessed by an accessor method, in 
an object situation, the use of 'our' should be rare.

Similarly in an ordinary package, you wouldn't normally expose a package 
variable unless you had a good reason, probably to configure something 
basic in the package.

Am I correct?





More information about the Wellington-pm mailing list