SPUG: Predeclaring packages

DeRykus, Charles E charles.e.derykus at boeing.com
Sat Jan 3 12:14:08 PST 2009


 

> Thanks for the explanation but your INIT block also exposes a value 
> for $greeting within the scope of the INIT block, correct...? whereas,

> without ensuring that $greeting gets set in that particular scope, if 
> you had said this for instance:

>> 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, 

  our $global = 'waiter';                  
  {                          
    our $global = 'server';                     
    # code here sees  'server'
  }
  # code here still sees server

  vs. lexical     {  my $foo = "foo";  
                    # only code here sees 'foo' ...  }
                  }


>    use strict;
>    use warnings;
>    
>    Hello::sayHi();
>    exit(0);
> 
>    package Hello;
>    INIT { our $greeting = 'Hello there'; }
>    sub sayHi { print $greeting . "\n" }
> 
> This'll enerate expected errors  ====>  
>     Variable "$greeting" is not imported ...
>     Global symbol "$greeting" requires explicit package name ...
> 
> ?

> The INIT block is one scope; the sayHi subroutine is another scope.
That code sample sets the value of $greeting 
> globally, but only declares $greeting in the INIT block.


> use strict;
> use warnings;

> Hello::sayHi();
> exit(0);

> package Hello;
> INIT { our $greeting = 'Hello there'; }
> sub sayHi { our $greeting; print $greeting . "\n" }

> produces:
> Hello there


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" }
}


-- 
Charles DeRykus


More information about the spug-list mailing list