SPUG: Predeclaring packages
Christopher Howard
choward at indicium.us
Fri Jan 2 15:33:44 PST 2009
On Thu, 1 Jan 2009, Yitzchak Scott-Thoennes wrote:
> On Wed, December 31, 2008 7:36 pm, Christopher Howard wrote:
>> Question: Is there a way to predeclare packages, without moving the
>> package to a separate file?
>>
>> This is my issue: When I write a script, I like to use packages to keep
>> everything nice and neat. And I like to have subs and packages after the
>> 'initializing' part of the program, so it is easy to find. So what I'm
>> doing now is something like this:
>>
>> ### EXAMPLE START ###
>
>> This doesn't work because $timer is not predeclared along with the
>> subroutines.
>
> There's something you're missing, but I'm not completely sure
> what it is. Can you explain more what isn't working?
>
> Your example should work just fine, though the predeclarations
> are unnecessary. Remember that first your entire script is compiled,
> including the sub definitions, and then it begins executing.
>
>
Blah!! You're right, I tried it again and it worked! (Figures...)
I did some more experimentation, and I think I know what was confusing me.
Maybe you can confirm this: the scoping for an 'our' statement occurs
during compiling, but actual variable assignments occur during runtime.
For example, I tried this:
### EXAMPLE START ###
use strict;
use warnings;
$Hello::greeting = 'Hello there';
Hello::sayHi();
exit(0);
package Hello;
{
our $greeting;
sub sayHi { print $greeting . "\n" }
}
### EXAMPLE END ###
This program outputs 'Hello there'. But if I move the value assignment
inside the package, it doesn't work like I want:
### EXAMPLE START ###
use strict;
use warnings;
Hello::sayHi();
exit(0);
package Hello;
{
our $greeting = 'Hello there';
sub sayHi { print $greeting . "\n" }
}
### EXAMPLE END ###
That outputs the 'use of an unitialized variable...' warning. I'm guessing
that is because nothing has been assigned to the package
variable $greeting when sayHi is called, and so 'use warnings' spits out a
warning for attempting to use an variable without first initializing it.
Am I getting it right?
--
Christopher Howard
http://indicium.us
More information about the spug-list
mailing list