I’ve been doing a lot of Perl development for my latest project, and I wanted to use a single config file for many scripts.

Using a single config file in a basic Perl script is pretty straightforward – you simply use a require statement to read the external file, and the variables contained within are automatically imported. (Though if you’re using strict, you’ll need to declare them using the “our” keyword.)

A problem arises when you want to use those global variables in a package file, though – because a Package has its own namespace, variables declared in your external config file are not imported into your module, even if you use the “our” keyword.

Fortunately, I was able to find a solution here, courtesy of Jeff Pang.

Here are a couple of examples.

The simple way to share variables between Perl scripts using “require”

File test.include.pl

$var = ".j.a.p.h.";

File test.pl

use strict;
require "test.include.pl";
our $var;
print "VAR is $var\n";

After creating the two files above and running test.pl, the output is:

eddie@widmers:~/wrk/$ ./test.pl
VAR is .j.a.p.h.

The more advanced way of sharing variables with a Perl Package
This method involves declaring the config file as a package, and then explicitly exporting the variables you’re interested in. Your other scripts and modules will then import those variables, making them available in that scope.

In this case, the config variable package will look something like this:

package SiteConfig;
require Exporter;

our @ISA = qw(Exporter);
our @EXPORT=qw($var $vare);

our $var = ".j.a.p.h.";


While the package you’re looking to use the variables in will look something like this:

package TestTest;
use TestConfig;
print "Var is $var\n";

sub new
   my $package = shift;
   print "VAR is $var\n";
  return bless({}, $package);

Of course, your particular needs will vary, so you’ll need to use your noodle to modify the above as necessary.