Your constructor new needs to return a blessed reference to the data structure you are using to contain the object's information. You have no relevant data here, but you still need to return something
bless associates the data with a specific package. In this case, your object should be blessed into MyModule, so that perl knows to look for MyModule::say_hello when it sees a method call like $myObj->say_hello()
Your current constructor returns the value returned by the print statement, which is 1 if it succeeded, as it almost certainly does. That is why you see the "1" in the error message
Can't locate object method "say_hello" via package "1" (perhaps you forgot to load "1"?) at ./main.pl line 8.
The most common container for an object's data is a hash, so you need to change new to this
sub new {
print "calling constructor\n";
my $self = { };
bless $self, 'MyModule';
return $self;
}
and then your program will work as it should. It creates an anonymous hash and assigns it to the $self variable, then blesses and returns it
Note that this can be made much more concise:
Without a return statement, a subroutine will return the value of the most recently executed statement
By default, bless will bless the data into the current package
There is no need to store the reference in a variable before blessing it
So the same effect may be achieved by writing
sub new {
print "calling constructor\n";
bless { };
}
Note also that your call
my $myObj = new MyModule()
is less than ideal. It is called indirect object notation and can be ambiguous. It is better to always use a direct method reference, such as
my $myObj = MyModule->new()
so as to disambiguate the call
new MyModuleis called indirect object notation and is generally considered bad practice in Perl because it can confuse the parser and cause non-obvious problems. I would recommend getting into the habit of sayingMyModule->newinstead. - Dave SherohmanMooseand its derivatives. I continue to achieve far better results using Perl to teach OO instead of something like Java or C++, simply because the concepts are so open and clear. - Borodinbless, and there is no day-to-day work. Learning aboutMoose, or preferably its minor variants, should build on top of a thorough understanding of Perl, and I strongly disagree that "This ist he perfect time for you to learn about Moose". - Borodin