How can I include another Perl script in my base Perl script?
I have a primary source file test.pl
and I want to include secondary sóurce file config.pl
within it.
What is a standard method to achieve this in Perl?
How can I include another Perl script in my base Perl script?
I have a primary source file test.pl
and I want to include secondary sóurce file config.pl
within it.
What is a standard method to achieve this in Perl?
(I'm guessing that the program called config.pl
sets config values that you want to access in test.pl
. You don't make that clear in your question.)
A simple example. If config.pl
looks like this:
#!/usr/bin/perl
$some_var = 'Some value';
Then you can write test.pl
to look like this:
#!/usr/bin/perl
use feature 'say';
do './config.pl';
say $some_var;
But this is a terrible idea for many reasons. Not least because it stops working when you add use strict
and use warnings
to either of the files (and you should aim to have use strict
and use warnings
in all of your Perl code).
So what's a better approach? Turn your configuration into a proper module that returns a hash (I only have a single scalar variable in my example above, but a hash gives you a way to deliver many values in a single variable). A simple approach might look like this.
A module called MyConfig.pm
:
package MyConfig;
use strict;
use warnings;
use parent 'Exporter';
our @EXPORT = qw[config];
sub config {
my %config = (
some_var => 'Some value',
);
return %config;
}
1;
And a test.pl
like this:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use FindBin '$Bin';
use lib $Bin;
use MyConfig;
my %config = config();
say $config{some_var};
Having got that working, you can add improvements like parsing the %config
hash from an external file (perhaps stored in JSON) and then allowing different configurations for different environments (development vs production, for example).
It's a little bit more work than your current approach, but it's far more flexible. And you can use strict
and warnings
.