I'm betting you're having a namespace issue. It would be handy to have a stripped down version of your code to look at, but here's my stab in the dark at what's going on.
__START_OF_COMMON_LIB_FILE__ package Class1; sub new { return bless({}, 'Class1'); } sub method_1 { print "I'm method 1!\n"; } package Class2; sub new { return bless({}, 'Class2'); } sub method_2 { print "I'm method 2!\n"; } 1; __END_OF_COMMON_LIB_FILE__
This will compile and run fun. You can create an object from class1 or class2. However, class1 will only be able to utilize the method1 sub and class2 will only be able to utilize the method_2 sub. The following code:
use lib 'C:\tmp'; use CommonLib; my $class1_obj = Class1->new; my $class2_obj = Class2->new; $class1_obj->method_1; $class2_obj->method_2;
Creates this output (note I've named my script tmp.pl):
D:\tmp>tmp.pl I'm method 1! I'm method 2! D:\tmp>
However, let's change the script so that Class1 tries to use method_2 and vice versa:
use CommonLib; my $class1_obj = Class1->new; my $class2_obj = Class2->new; $class1_obj->method_2; $class2_obj->method_1;
We get this output:
D:\tmp>tmp.pl Can't locate object method "method_2" via package "Class1" at D:\tmp\t +mp.pl line 10. D:\tmp>
This is because method_2 is only in the namespace for Class1. If you want a method that is defined in the file to be usable by both classes, you will have to define it for both classes.
So in short, the only functions your classes will be able to access are the functions that are between their package declaration and the next package declaration. If you declare two packages in a row at the top of the file like:
package Class1; package Class2; sub foo { }
Then only the last declared package will have access to the functions you are defining. In the above case, you will be able to use Class2->foo, but Class1->foo will result in the same can't locate object error. As a matter of fact, Class1 will have no methods available since its namespace immediately ends.
In reply to Re: use a package multiple times
by tj_thompson
in thread use a package multiple times
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |