Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: the "our" declaration ?!!

by LanX (Saint)
on Jan 20, 2009 at 10:57 UTC ( [id://737543]=note: print w/replies, xml ) Need Help??


in reply to the "our" declaration ?!!

"our" has exactly the same scope like "my", it's the exact analogon but for package variables.

If the compiler encounters a simple* variable name like $var it has to decide where to store and look up it's value. This is decided by the last "declaration"¹ (my or our) within the same "lexical scope", which doesn't necessarily mean the variable itself is "lexical" (that means: private to the lexical scope).

use warnings; use strict; $\="\n"; $,="\t"; our $x="main"; { package one; our $x="one"; package two; our $y="two"; { my $x="private"; print $x,$y; # private $x , $two::y } # end of second scope print $x,$y; # $one::x , $two::y } # end of first scope print $x; # $main::x print $one::x; # variable still exists in that namespace # without being bound to $x # but the private $x of the second scope # is definitely lost! # end of file scope __END__ private two one two main one
So "our" gives you a much more orthogonal behavior to "my" than simply relying on "simple variables are by default packagevars except when declared with my"².

Cheers Rolf

UPDATES: extended code example

(*) "simple" means without explicit package name e.g. $package::var

(¹) I'm not sure if "declaration" is the best term, maybe better "binding" or "aliasing", the perldoc talks about "associating"

(²) without "strict" or "vars"

well the explanation in "perldoc -f our" is quite good!

"our" associates a simple name with a package variable in the current package for use within the current scope. When "use strict ’vars’" is in effect, "our" lets you use declared global variables without qualifying them with package names, within the lexical scope of the "our" declaration. In this way "our" differs from "use vars", which is package scoped.

Unlike "my", which both allocates storage for a variable and associates a sim‐ ple name with that storage for use within the current scope, "our" associates a simple name with a package variable in the current package, for use within the current scope. In other words, "our" has the same scoping rules as "my", but does not necessarily create a variable.

...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://737543]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 03:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found