SPUG: Predeclaring packages

Ronald J Kimball rjk-spug at tamias.net
Sat Jan 3 09:03:22 PST 2009


On Sat, Jan 03, 2009 at 02:50:09AM -0800, DeRykus, Charles E wrote:
>  
> 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.

>    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


Ronald


More information about the spug-list mailing list