Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

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

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
";

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...