SAJITHA MARIYAM SAJITHA MARIYAM - 3 months ago 11
Perl Question

What is the meaning for the error "cant locate object method via package" in perl?

I have declared two classes baseclass - chocolatecake.pm, derived class - birthdaycake.pm in perl language. the following error is shown. can anyone please explain what this error means??
code for reference:

base class:

#!usr/bin/perl
package chocolate_cake;
sub new
{
$class=shift;
$self={};
bless($self,$class);
return $self;
}

sub bake
{
print "The cake is backing\n"
}
sub frose
{
print "The cake is frosing\n";
}
sub put_handle_on

{
$self=shift;
$numOfCan=shift;
print "The $numOfCan in chocalate cake\n";
}
1;


derived class:

package birthday_cake;
@ISA = (chocalate_cake);
sub new
{
$class=shift;
$self={};
bless($self,$class);
return $self;
}
sub put_candles_on
{
my $self=shift;
my $numOfCan=shift;
print "The $numOfCan in birthday cake\n";
}
1;


main function

use birthday_cake;
use Scalar::Util 'blessed';

$cake_bi=new birthday_cake();
print blessed($cake_bi),"\n";
$cake_bi->bake();


I am getting the following error:

Can't locate object method "bake" via package "birthday_cake" at main.pl

Answer

Two problems here:

  • chocalate_cake and chocolate_cake are two different strings.
  • your birthday_cake.pm is missing use chocolate_cake.

Also, it'll help you in the future if you get into the habit of using strict and warnings in all your scripts.

Writing birthday_cake->new is safer then the "indirect object syntax" you used (and if you're paranoic, you can use 'birthday_cake'->new as I usually do, or even birthday_cake::->new, especially when you don't use Capitalized class names).

Comments