SPUG: Predeclaring packages

DeRykus, Charles E charles.e.derykus at boeing.com
Sat Jan 3 16:18:25 PST 2009


 
On Sat, Jan 03, 2009 at 12:14:08PM -0800, DeRykus, Charles E wrote:
>  
> >> I wouldn't say that $our exposes a value for $greeting - it simply
> exposes $greeting itself.
> 
> Not to overdo semantics but the docs say 'our' exposes a value ..
> maybe just to emphasize that the global value set by 'our', although 
> similar in some ways to a lexical 'my',  behaves differently, eg,

>> perldoc -f our states:

>>  "our" associates a simple name with a package variable in the
current
>>  package for use within the current scope.

>> If some place in the documentation suggests that 'our' exposes a
value, I'd argue that's misleading and should be clarified.  :)

Maybe the word's a bit over-exposed :)


> You're right but the compile/runtime issues gets confusing to me 
> anyway because setting the global $Hello::greeting at runtime does 
> work but not via 'our'.
>   
> 
> #our $greeting = 'Hello there';     # not ok
> $Hello::greeting = 'Hello there';   # ok
> Hello::sayHi();
> exit(0);
> 
> package Hello;
> { our $greeting;
>   sub sayHi { our $greeting; print $greeting . "\n" } }

>> The documentation mentioned the "current package".  The commented-out
line in your code snippet is in the 
>> package main, not the package Hello.


>> our $greeting = 'Hello there';
>> Hello::sayHi();
>> exit(0);

>> package Hello;
>> sub sayHi { print $main::greeting . "\n" }


Ah.. that should explain it but I see in the Camel, pg. 756:

  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 located is determined at the
  point of declaration, not at the point of use. This means the follow-
  ing behavior holds  and is deemed to be a feature:

  package Foo;
  our $bar      # $bar is $foo::bar for rest of lexical scoope
  $bar = 582;

  package Bar;
  print $bar;   # prints 582, just as if "our" had been "my"

Hm, seems as if the lexical scope of $greeting should make the package 
qualification unnecessary ... 

Stranger yet it appears to work here:

   perl -wle 'our $x = 3; Foo::foo();  package Foo; sub foo { print
$x};'
   3

-- 
Charles DeRykus


More information about the spug-list mailing list