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

Categories

0 votes
781 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...