From Robin's Wiki

PerlTips: ConfigurationOptionsFromModules

I have a program that has a bunch of default settings that I want to be able to selectivly override based on an external file, perhaps mentioned on the command line or something (i.e. no prior knowledge).

This also allows code to be inserted into the module to do something very domain specific.

To do this, declare the variables using our rather than my. For example:

subset of main.pl:

our $label = "default label";
our $optionalSub = undef;

And then the module can be:

config.pm:

$label = "test #3";
$optionalSub = \&theSub;
<:vspace>
sub theSub {
        # code goes here
}

The main program then can load this with:

subset of main.pl:

unless (my $ret = do $config) {
        die "couldn't parse $config: $@" if $@;
        die "couldn't do $config: $!"    unless defined $ret;
        die "couldn't run $config"       unless $ret;
}

The variables can then be used just as if they were defined locally, and the sub can be called like:

subset of main.pl:

if (defined($optionalSub)) {
        $optionalSub->(...options go here...);
}
Retrieved from http://www.kallisti.net.nz/PerlTips/ConfigurationOptionsFromModules
Page last modified on September 18, 2010, at 11:54 AM