How to create a configuration file that automatically adds global modules for all pages

I am creating an internal / web automation tool using perl with apache. It is hosted in a Windows environment. My question is to deal with many pages in which everyone has common modules. Instead of manually adding each module for each page, is it possible to have a “global module” for all the modules that will be available for the pages?

For example, if I need to add new modules and have 10 pages, instead of going to each page and adding using New :: Package; Is it possible to do this in 1 configuration file, which will make New :: Package available for each file that uses this configuration module?

I did this with PHP, where you include / require in some init script, and then just include the init script on each page in it.

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 

TL; DR: Can you have a configuration module import multiple modules / packages into pages containing only this magic configuration module?

Edit: I would like to add that I'm pretty new to perl, so if this is an obvious thing, easy :)

+4
source share
1 answer

This is not at all obvious. The Exporter module provides an export_to_level function that can help solve this problem. Typically, using an Exporter (i.e., creating a package of a subclass of Exporter ) exports the characters to the calling package. The export_to_level method allows export_to_level to export characters to a package above the stack trace, which 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 instead of talking

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

in each of the dozens of scripts, you just say

 use Module1234; 

So here is what Module1234.pm might look Module1234.pm :

 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; 

Call now

 package MyPackage; use Module1234; 

in your script it will load the remaining four modules and process the export of all the desired functions to the MyPackage package and

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

enough to output the output of "FOOBARBAZ" .

+4
source

Source: https://habr.com/ru/post/1496641/


All Articles