SPUG: Predeclaring packages

Christopher Howard choward at indicium.us
Wed Dec 31 19:36:39 PST 2008


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

#!/usr/bin/env perl

#sub preclarations
sub Explosive::build;
sub Explosive::set;
sub Explosive::detonate;

# Master Control Program start #

Explosive::build();
Explosive::set();
Explosive::detonate();

exit(0);

# Master Control Program end #

package Explosive;

sub build { ... }
sub set { ... }
sub detonate { ... }

### EXAMPLE END ###

This works fine. However, if I want to add package variables, with 
convenient 'our' statements, I run into a problem. Say, I re-write the 
program:

### EXAMPLE START ###

#!/usr/bin/env perl

#sub preclarations
sub Explosive::build;
sub Explosive::set;
sub Explosive::detonate;

# Master Control Program start #

$Explosive::timer = 'clock';

Explosive::build();
Explosive::set();
Explosive::detonate();

exit(0);

# Master Control Program end #

package Explosive;
{

our $timer;

sub build { ... # include $timer # ... }
sub set { ... # set time on $timer # ... }
sub detonate { ... # when #timer runs out # ...}

}

### EXAMPLE END ###

This doesn't work because $timer is not predeclared along with the 
subroutines. I can move the package to the beginning of the script, but 
that is not what I want. Or I can declare $timer at the beginning of the 
script separately as $Explosive::timer, but then I have to use 
$Explosive::timer inside of each subroutine instead of $timer, which is 
blinkin' annoying, especially if I want to change the name of the package.

I was trying to use a goto with labels, to run through the package code 
before the earlier code, but I couldn't seem to get that to work. (Maybe 
it's because I'm not really sure what a label is supposed to look 
like... Didn't seem to work like the examples on the internet...)

-- 
Christopher Howard
http://indicium.us


More information about the spug-list mailing list