This is an interesting Perl behaviour. (atleast to me :) )
I have two packages PACKAGE1
and PACKAGE2
which exports function with same name Method1()
.
As there will be so many packages which will export this same function, use
-ing everything in a Perl file will be tedious. So, I have created a general include file INCLUDES.pm
which will have these use
s.
INCLUDES.pm:
use PACKAGE1;
use PACKAGE2;
1;
PACKAGE1.pm:
package PACKAGE1;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw (
Method1
);
sub Method1{
print "PACKAGE1_Method1 \n";
}
1;
PACKAGE2.pm:
package PACKAGE2;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw (
Method1
);
sub Method1{
print "PACKAGE2_Method1 \n";
}
1;
Tests.pl:
##################first package################
package Test1;
use INCLUDES;
my @array = values(%INC);
print "@array \n";
Method1();
##################second package################
package Test2;
use INCLUDES; #do "INCLUDES.pm";
my @array = values(%INC);
print "@array \n";
Method1();
The motive is, only the latest package's Method1()
should be used in any Perl file.
The output surprises me.
I would expect that both Method1()
calls in Tests.pl
should be success.
But only the first Method1()
executes, the second Method1()
call says "undefined".
OUTPUT:
C:/Perl/site/lib/sitecustomize.pl PACKAGE1.pm C:/Perl/lib/Exporter.pm PACKAGE2
.pmINCLUDES.pm
PACKAGE2_Method1
C:/Perl/site/lib/sitecustomize.pl PACKAGE1.pm C:/Perl/lib/Exporter.pm PACKAGE2
.pm INCLUDES.pm
Undefined subroutine &Test2::Method1 called at C:\Temp\PackageSample\Tests.pl line 15.
Do somebody have any answers/views on this?
The actual scenario:
the methods in multiple Perl modules will be having same name. But the methods from the High preference perl module should only be used.
For example, if PACKAGE1
contains Method1(), Method2()
& PACKAGE2
contains only Method1()
, then Method1()
should be used from PACKAGE2
& Method2()
should be used from PACKAGE1
Basically I want to achieve a Hierarchy among modules based on Preference. Is there any way for this?