in reply to
Variables in Common parent class
Some problems with the code shown:
- $self is a class variable, it should be an object (instance) variable.
- Subroutines have unneccessary prototypes.
- use strict and use warnings are missing.
- Module names should be capitalised.
But the main problem is the structural relationship of the child classes to the parent class. Here is one way to do what is wanted:
#! perl
use strict;
use warnings;
#---------------------------------------------------------------------
+---------
{
package SuperModule;
sub new
{
my ($class, %params) = @_;
my $self = { dbh => $params{DB} };
return bless $self, $class;
}
sub print_super
{
my ($self) = @_;
print 'Super module: ', $self->{dbh}, "\n";
}
}
#---------------------------------------------------------------------
+---------
{
package MyModule;
our @ISA = qw( SuperModule );
sub new
{
my ($class, %params) = @_;
my $self = SuperModule::new($class, %params);
$self->{file_name} = $params{'file name'};
return bless $self, $class;
}
sub print_file
{
my ($self) = @_;
print 'My file name from file obj ', $self->{file_name}, "\n";
}
}
#---------------------------------------------------------------------
+---------
{
package YourModule;
our @ISA = qw( SuperModule );
sub new
{
my ($class, %params) = @_;
my $self = SuperModule::new($class, %params);
$self->{block_name} = $params{'block name'};
return bless $self, $class;
}
sub print_block
{
my ($self) = @_;
print 'My block name from block obj ', $self->{block_name}, "\
+n";
}
}
#---------------------------------------------------------------------
+---------
my %f_params = (
DB => 'File DB value',
'file name' => 'Lisa',
);
my %b_params = (
DB => 'Block DB value',
'block name' => 'Pisa',
);
my $file_obj = MyModule ->new(%f_params);
my $block_obj = YourModule->new(%b_params);
$file_obj ->print_super();
$file_obj ->print_file();
$block_obj->print_super();
$block_obj->print_block();
Output:
13:56 >perl 567_SoPW.pl
Super module: File DB value
My file name from file obj Lisa
Super module: Block DB value
My block name from block obj Pisa
13:56 >
Hope that helps,
Update: ++tobyink, below, for the improvements to the child class constructors.