Perl: can’t locate object method bar via package

perlperl-module

I am new to this site, so bear with me, If this question has already been answered somewhere else already. I am trying to call a subroutine "bar" from a module "codons1.pm" , and I encounter the error:
Can't locate object method "bar" via package "codons1.pm" (perhaps you forgot to load "codons1.pm"?). The main script looks like:

use strict;
use warnings;
my $i = 1;
my $pack = "codons$i\.pm";
require $pack;
(my %temp) = $pack->bar();
print keys %INC ;

Thanks to (Perl objects error: Can't locate object method via package) , I was able to verify using %INC, that the module is loaded.
The module looks like:

package codons1;
sub bar{ #some code; 
return (%some_hash);}
1;

I am using $i so that I can load multiple similar modules via a loop. Any suggestions is welcome and thanks a lot, in advance.

Best Answer

Your package is codons1, and you're trying to call codons1.pm->bar. Either of the following will work correctly:

my $pack = "codons$i";
require "$pack.pm";
$pack->bar();

or

my $pack = "codons$i";
eval "require $pack";
$pack->bar();
Related Topic