How to have a config file automatically add 'global' modules for all pages

apache, perl, windows

Solution

This is not an obvious thing at all. The `Exporter` module provides an `export_to_level` function that can help with this problem. Normally, using `Exporter` (i.e., making a package a subclass of `Exporter`) exports symbols into the calling package. The `export_to_level` method makes it possible to export symbols into a package higher up the stack trace, which is what you want to do here. Here's a proof-of-concept:

First some modules with exported functions:

# Module1.pm
package Module1;
use base 'Exporter';
our @EXPORT = ('foo');
sub foo { "FOO" }
1;

# Module2.pm
package Module2;
use base 'Exporter';
our @EXPORT_OK = ('bar');
sub bar { "BAR" }
1;

# Module3.pm
package Module3;
use base 'Exporter';
our @EXPORT_OK = ('baz');
our %EXPORT_TAGS = ('all' => [ 'baz' ]);
sub baz { "BAZ" }
1;

And rather than have to say

use Module1;
use Module2 'bar';
use Module3 ':all';
use Module4;         # some other module that doesn't need to export anything

in every one of dozens of scripts, you'd rather just say

use Module1234;

So here's what `Module1234.pm` might look like:

package Module1234; # optional
use Module1;
use Module2;
use Module3;
use Module4;

# these commands could go inside an  import  method, too.
Module1->export_to_level(1, __PACKAGE__);
Module2->export_to_level(1, __PACKAGE__, 'bar');
Module3->export_to_level(1, __PACKAGE__, ':all');
1;

Now calling

package MyPackage;
use Module1234;

in your script will load the other four modules and handle exporting all of the desired functions to the `MyPackage` package, and

use Module1234;
print foo(), bar(), baz();

is enough to produce the output `"FOOBARBAZ"`.

Problem

I am building an internal automation/web tool using perl with apache. It is hosted in a windows environment. My question is when dealing with many pages that all have common modules. Instead of manually adding each module for each page, is it possible to have a 'global module' pull in all modules that will be available to the pages? For example, if I need to add a new modules and there are 10 pages, instead of going into each page and adding use New::Package; is it possible to do this in 1 config file that will make the New::Package available to each file that uses this config module? I have done this with PHP, where you include/require in some init script and then simply include that init script on each page. ``` Package MyProj::Configuration use package1; ... use package999; ``` ``` # Main Page use MyProj::Configuration; # Now all modules are included in this page, without needing to add them manually ``` TLDR: Can you have a configuration module import multiple modules/packages into pages that only include this magic configuration module? Edit: I would like to add that I am fairly new to perl, so if this is an obvious thing, go easy :)

Original source