30章 Perlでオブジェクト指向 継承の書き方 その2

myでメンバーデータを定義してみましょう。
親クラス ファイル名:Human.pm

package Human;

use strict;

my $a;
my $b;
###########
sub new
{
my $class = shift;
my $args = shift;
my $self = {};
bless($self, $class);
return $self;
}
###############
sub set
{
my ($self,$x, $y)  = @_ ;
$a = $x;
$b = $y;
}
###############
sub calc2
{
my ($self)  = @_ ;

my $c = $a + $b ;
print “Human->calc2 = $c \n”;
}
##############
1;

子クラス ファイル名:Student.pm

package Student;

use strict;

# 1つだけ(StudentはHumanだけ)を継承する場合に使えるテクニック
use base qw( Human );
###########
sub new
{
my $class = shift;
my $self = Human->new();
bless($self, $class);
return $self;
}
##############
1;

実行ファイル名:test1.pl

use strict;
use Data::Dumper;
use Student;

my $man = Student->new();
$man->set( 1 ,2 );
$man->calc2( );

実行結果:

 >perl test1.plHuman->calc2 = 3

メンバーデータ$a,$bも
Studentに継承されているのがわかります。
継承らしく見える。