perl

How to call method in base class in Perl


I am getting the error:

Can't locate object method "add" via package "child1" at ./test.pl line 8.

I want to access the base class add method and I am getting this above error

child.pm

#!/usr/bin/perl
package child1;
use strict;
use warnings;
use Exporter;
use parent;
my @ISA=qw(cal Exporter);
sub new{
        my $class=shift;
        my $ref=cal->new();
        bless ($ref,$class);
        return $ref;
        }
sub add{
        my $ref=shift;
        print "This is from child class";
        my($a,$b)=@_;
        return ($a+$b); 
        }

parent.pm

#!/usr/bin/perl
package cal;
use strict;
use warnings;
use Exporter;
my @EXPORT=qw(add);
my @ISA=qw(Exporter EXPORT);
sub new{
        my $class=shift;
        my $ref=[];
        bless ($ref,$class);
        return $ref;
        }

sub add{
        my $ref=shift;
        my $a=shift;
        my $b=shift;
        return ($a+$b);
        }
1;

test.pl

#!/usr/bin/perl
use strict;
use warnings;
use Exporter;
use child;
my @ISA=qw(child1 Exporter);
my $obj=new child1();
my $sum=$obj->add(1,2);
print "$sum=sum";

Solution

  • The .pm modules do not need, and likely do not want, the #!/usr/bin/perl lines. This is only for programs intended to be executed from the command line, like your .pl module. While you may 'perl -cw' your .pm modules, or do other command line debugging with them, such is not normal "production" use.

    And .pl modules should not have @ISA, or other "our" declarations found in packages nor any exporter related things.

    As said before, change "my"s for package stuff to "our"s. The "my" hides things to outsiders as if the statements were never there.

    In the "cal" class, do you want something like the following? I favor SUPER as it really shows what is going on and is much more generic.

    package child1;
    use Exporter;
    our @ISA=qw(cal Exporter);
    
    sub new{
            my $class=shift;
            my $ref=<b>$class->SUPER::new()</b>;
            return $ref;
            }
    

    One final point: you may need a "\n" on the final print statement. Without it the buffer may not flush correctly on exit in some environments so you will never see the output.