Reputation: 15
I'm trying to call a function from a package that has the same name with another package in different directory, and the functions are the same name also.
Explanation:
let's say that i have package1.pm
that exists in dir1/
as dir1/package1.pm
inside it sub fun1
is the one that i want to call
package package1;
sub fun1($$$)
{
#anything;
}
the second package is inside anothee dir: dir2/package1.pm
package package1;
sub fun1($$$)
{
#anything;
}
suppose that the functions will take the same number of parameters.
is there any way to call the function that i want exactly?
Upvotes: 0
Views: 112
Reputation: 1030
I'll start of by saying that the way I'm suggesting is highly not recommended and will bring up a warning.
The most naive way that comes to my mind to do what you're asking is using do
:
unshift @INC, "yourpath/dir1";
do 'package1.pm';
package1::sub1();
shift @INC;
unshift @INC,"yourpath/dir2";
do 'package1.pm';
package1::sub1();
Let's say that sub1
prints the current directory, so the output will look like this:
dir1
Subroutine sub1 redefined at yourpath/dir2/package1.pm line 8.
dir2
Again, don't use that unless you don't care for some reason for warnings. It's a bad practice that can cause a lot of future bugs.
Why it works:
do
loads the code and doesn't remember that it loaded it, meaning that in another invocation of do
with a package of the same name, it will be overriden. Usually you won't use do
, but require
that does remember it loaded a package. The code attached uses do
twice. the second time overrides the first one which is why the output looks as it does.
Upvotes: 0
Reputation: 3535
I will suggest you to name the packages based on the directories (for eg Dir1::Package1
, Dir2::Package1
) on which they are; and keep them into same base (/lib in this case) directory:
/lib--
|
---/Dir1--
| |
| --Dir1::Package1
|
|
---/Dir2--
|
-- Dir2::Package1
Then in the script you can fully qualify the subroutine name to call from those packages according to your wish:
#!/usr/bin/perl
use strict;
use warnings;
use lib qw(./lib);
use Dir1::Package1;
use Dir2::Package1;
# call from Dir1 Package1
Dir1::Package1::fun();
# call from Dir2 Package1
Dir2::Package1::fun();
Upvotes: 1