Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: can't locate object method bar via package

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.

like image 437
bala83 Avatar asked Jun 15 '14 09:06

bala83


2 Answers

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();
like image 50
RobEarl Avatar answered Oct 03 '22 09:10

RobEarl


A better way to do what you're trying to achieve

#!/usr/bin/perl
use strict;
use warnings;
package codons1;
sub new {
    my $class = shift;
    return bless {}, $class;
}
sub bar {
    my %some_hash = (temperature=>"35");
    return %some_hash;
}
1;
package main;
my $object = codons1->new(); #creates the object of codons1
my %temp = $object->bar(); #call the bar method from codons1's object
print keys %temp;

Demo

You need to learn basic object oriented programming in Perl. Start with perlootut, and then perlobj. Read the Object Oriented Perl chapter from freely available Beginning Perl book.

like image 45
Chankey Pathak Avatar answered Oct 03 '22 07:10

Chankey Pathak