Adam Adam - 3 months ago 14
Perl Question

Perl - Can't locate object method via "Module::SUPER"

This is my first time using OOP with perl. I am in the processes of refactoring a 4k line procedural program at work. It seems pretty straight forward but I am having an issue with inheritance and SUPER.

Error message:


"Can't locate object method "New" via package "Module::SUPER" at Module.pm line 10"


I have tried, use base, parent and setting @ISA but they all get the same error. I'm sure I have to be overlooking something.

(This is not code from the program I am working on. Just an example that produces the same error)

All .pm and .pl files are in the same directory in this example. In the program I am working on the main program is in bin and the modules will be in ../modules(relative to bin).

I would assume this would be all I need to make that work:

use lib "../modules";


If I am wrong in thinking that please let me know.

Parent Module

package BaseModule;
use strict;
use warnings;
sub new {
my $class = shift;
my $self = {
ARRAY => shift,
DIVIDER => ","
};
bless ($self, $class);
return $self;
}
sub array {
my $self = shift;
if(@_) { $self->{ARRAY} = shift };
return $self->{ARRAY};
}
sub divider {
my $self = shift;
if(@_) { $self->{DIVIDER} = shift };
return $self->{DIVIDER};
}
sub testSub {
my $self = shift;
print join($self->{DIVIDER}, @{ $self->{ARRAY} } );
return 1;
}

1;


Child Module

package Module;
use strict;
use warnings;
#use base qw(BaseModule);
#require BaseModule;
#our @ISA = qw(BaseModule);
use parent qw(BaseModule);
sub new {
my $class = shift;
my $self = $class->SUPER::New(@_);
$self->{STRING} = shift;
bless ($self, $class);
return $self;
}
sub string {
my $self = shift;
if(@_) { $self->{STRING} = shift };
return $self->{STRING};
}
sub testSub {
my $self = shift;
print "$self->{STRING}:\n";
$self->SUPER::testSub();
return 1;
}
1;


Do I need to bless the child class if the parent class returns an already blessed $self?

Main Script

#!/usr/bin/perl
use strict;
use warnings;
use Module;

my $module = Module->new([1, 2, 3, 4, 5], "Example");
$module->divider(" | "); # Test Changing divider;
$module->testSub();


Any help is greatly appreciated.

Answer
"Can't locate object method "New" via package "Module::SUPER" at Module.pm line 10"

You try to call BaseModule::New whis hasn't been defined (did you mean BaseModule::new? Perl is case sensitive).

Do I need to bless the child class if the parent class returns an already blessed $self?

No, $self at that point is already blesses (you could check that by means of Scalar::Util::blessed().