Sample code:
m1.pm
my $a;
my $b;
sub init {
$a = shift;
$b = shift;
}
sub printab {
print "a = -$a-\n";
print "b = -$b-\n";
}
1;
m2.pm
my $a;
my $b;
sub init {
$a = shift;
$b = shift;
}
1;
test.pl
use strict;
use warnings;
use m1;
use m2;
init('hello', 'world');
printab();
Run:
$ perl test.pl
a = --
b = --
$
What happens is that the init('hello', 'world') call is mapped to m2.pm and initializes the variables ($a and $b) there.
This kind of makes sense, but what I do not understand is why those values are not available in test.pl.
-
Is there something fundamentally wrong that I am trying to do here? What is the correct way to use two modules with same named subroutines and variables?
-
How exactly does a Perl
usework? It would help if someone could contrast it with C’s#includedirective.
First, do read perldoc perlmod.
You do not declare a namespace in either module, so everything is in the
mainnamespace. Declarepackage m1;inm1.pmandpackage m2;inm2.pm.At the very least, you should implement an
importmethod (or inherit the oneExporterprovides) so that programs that use modules can decide what to import from where.It also seems to me that you are exploring around the edges of OO.
Further:
Avoid using
$aand$bas variable names because it is easy to confuse them with the package variables$aand$bused bysort.Don’t use lower case module names: They are reserved for pragmata.
A minimal implementation (all in one file for testing convenience) looks like this: