Basically the file UtilLib.pm will look like this:(BTW your filename for require must be quoted.)# require outside the package so that its functions are # NOT imported into the UtilLib namespace, so that other # libraries can use them. require mysql_wrapper_lib.pl; package UtilLib;
Now with the code:# File mysql_wrapper_lib.pl $foo = 123; 1;
Where will your $foo end up? In package One, and not in package Two. Without the use statement in package One, or with package One loaded later, it will end up in package Two.package One; use UtilLib; package Two; use UtilLib;
Now imagine that package One and package Two are in two different modules, and loaded from various places. What package will $foo eventually end up in? Well, it'll probably be either in package One or in package Two, but which one?
And that's why use got support for import, so the same variables/functions can be aliased in any package you like. Problem solved.
# File Mysql_wrapper.pm package Mysql_wrapper; use base 'Exporter'; @EXPORT = qw($foo); $foo = 123; 1;
So now where will $foo end up in? Guess what: both in package One and in package Two. $One::foo and $Two::foo will actually point to the same variable, that's why they are called "aliases".package One; use Mysql_wrapper; package Two; use Mysql_wrapper;
p.s. It's not absolutely necessary to use Exporter, but it saves you from having to do the manual work of actually importing the variables yourself. That would end up to be a copy/paste job anyway, as it's not code that is easy to remember. Just to show it can be done (after all, we're here to learn right? :) ) here is some code that would do just that:
package Mysql_wrapper; $foo = 123; sub import { my $pkg = caller; no strict 'refs'; *{"$pkg\::foo"} = \$foo; # and the same for other variables... } 1;
In reply to Re: Good Module Design
by bart
in thread Good Module Design
by shemp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |