Perl – Error: “Can’t locate object method “new” via package” in Perl

moduleobjectperl

I'm new to Perl, so I'm having some problems with OOP.

I have…

  • connect4.pl
  • Player.pm

I'm trying to use module "Player" in connect4,pl, but I get the error: "Can't locate object method "new" via package" when I try to create an instance of the module.

I've read other posts, but I don't quite get what their problem was and how it was fixed…

Here is a snippets (I have deleted many lines, I just included what I thought was important)

use Player;

my $temp_connect_four = Player -> new("parameters");

and

package connect4;

sub new{
#some variables
}

#more methods/subroutines

What's the problem?

Best Answer

You need to have something like:

file: Player.pm

package Player;
use strict;
use warnings;
sub new {
    ...
}

your main script, connect4.pl

use strict;
use warnings;
use Player;
my $player = Player->new( ... args...);

EDIT

First answered only the above, but based on the fact, than you have problems understand how perl packages should be organized, IMHO you need some more comments, from the perl-beginner point of view (as me). You probably will get much better and much more precise answers from perl-gurus.

If you start learning OO with perl, IMHO, you should start using the "Mo" or "Moo" packages from CPAN. They provides to you some nice "sugar" what greatly helps you start making OO oriented programs in perl and allow you extend your packages later to Moo?'s smarter brother -> Moose.

Must say, it's not mean than you will not need to learn the basic principes of perl OO.

Because most of CPAN modules are written without Mo?se and many programs what you will read, are written in traditional perl-OO, so you sill need learn it, but (from my own experience) it needs somewhat steeper learning curve. You need to understand package structure, what is a "blessing" and so on. Using "Mo" (or Moose) helps you hide many things, and you will learn them later.

Using "Mo" helps you to have faster results withot fully understand - why it is working. ;) /Probably, now many perl-experts will comment this as a wrong method of learning. :)/

The Player example using "Mo" can be written as like the next:

File: Player.pm

package Player;
use strict;
use warnings;
use Method::Signatures::Simple;  # for automatic $self using "method" instead of the "sub"
use Mo;

has 'name';
has 'age';

method info {
        return "The player " . $self->name . " is " . $self->age . " years old.";
}
1;

file with the main.pl script:

use strict;
use warnings;
use feature 'say';
use Player;

my $player = Player->new(name => 'John', age => 15);

say $player->info();

running the main.pl produces:

The player John is 15 years old.

As you can see, the "Mo" provides you with a FREE "new" method. (and many other things too).

You really need to read:

Related Topic