Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl objects error: Can't locate object method via package

Tags:

object

oop

perl

I realise there are several questions like this out in the ether, but I can't a solution for my problem. Maybe I should improve my lateral thinking.

I have a module which I am testing. This module looks something like:

package MyModule;
use strict;
use warnings;

... # a bunch of 'use/use lib' etc.

sub new {
    my $class = shift;
    my ($name,$options) = @_;

    my $self = {
        _name     => $name,
        _features => $options,
        _ids      => undef,
        _groups   => undef,
        _status   => undef,
    };
    bless $self,$class;
    return $self;
}

sub init {
    my ($self) = @_;
    my ($ids,$groups,$status) = ...; # these are from a working module
    $self->{_ids}    = $ids;
    $self->{_groups} = $groups;
    $self->{_status} = $status;
    return $self;
}

This is my test file:

#!/usr/bin/perl -w

use strict;
use MyModule;
use Test::More tests => 1;
use Data::Dumper;

print "Name: ";
my $name;
chomp($name = <STDIN>);
print "chosen name: $name\n";

my %options = (
    option1 => 'blah blah blah',
    option2 => 'blu blu blu',
);

my $name_object = MyModule->new($name,\%options);
print Dumper($name_object);
isa_ok($name_object,'MyModule'); 

$name_object->init;
print Dumper($name_object);

Now it works down to the isa_ok, but then comes up with:

Can't locate object method "init" via package "MyModule" at test_MyModule.t line 31, <STDIN> line 1.

This has only occurred now that I'm trying (and somewhat failing it seems) to use objects. So thus I reckon I'm misunderstanding the applications of objects in Perl! Any help would be appreciated...

like image 910
dgBP Avatar asked Mar 28 '13 18:03

dgBP


1 Answers

I think you're loading a different file than the one you think you are loading.

print($INC{"MyModule.pm"}, "\n");

will tell you which file you actually loaded. (If the module name is really of the form Foo::Bar, use $INC{"Foo/Bar.pm"}.) Make sure the capitalisation of the package and the file name match.

like image 52
ikegami Avatar answered Nov 11 '22 02:11

ikegami