0

I am getting:

Can't call method "test" without a package or object reference at 4.pl line 6.

And i don't know why, any ideas?

Users.pm

package Users; 
sub new{
    print "Created\n"; 
}
sub test{
    print "a";
}
1;

Test.pl

BEGIN {
  push @INC,"/home/baddc0re/Desktop/perl_test/";
}
use Users;
$user = new Users();
$user->test();

2 Answers 2

3

I suggest to you use syntax $users = Users->new() instead of new Users. You forgot to bless values inside new method. Please read perlootut under perldoc.

Users.pm

package Users;

sub new {
    my $class = shift;

    my $self = {};
    bless $self, $class;
    return $self;
}

sub test {
    print "a";
}

1;

MAIN

use strict;
use Users;

my $users = Users->new();
print $users->test();
Sign up to request clarification or add additional context in comments.

Comments

3

Object construction in Perl doesn't work that way. The constructor has to explicitly return a reference that has been made into an object with the bless function; in fact, in Perl, this is what defines a constructor, as "new" is just another name for a subroutine and, unlike in C++, invoking a function named new does not force Perl to create an object. In this specific example, new is just returning the return value of print, which is presumably just some true value, and trying to invoke the test method on this value fails because it hasn't been blessed into any class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.