25章 Perlでオブジェクト指向 クラス内で別のクラスを使う

ここではStudentクラスの中でHumanクラスを利用しています。
new()の中でHumanのオブジェクト$manを作成し、
get()やshow()の中で利用しています。
また、show2()の中では、Humanのオブジェクト作成と利用を行っています。

ファイル名:Student.pm

package Student;use strict;
use Human;

my $man;

###########
sub new
{
my $class = shift;
my $self = {};
bless($self, $class);

$man = Human->new();
return $self;
}
#################
sub get
{
my ($self,$x, $y)  = @_ ;
$man->set($x,$y);
}
#################
sub show
{
my ($self)  = @_ ;
my $z = $man->calc2();
print “Student show = $z \n”;
}
#################
sub show2
{
my ($self,$x, $y)  = @_ ;
my $woman = Human->new();
$woman->set($x,$y);
my $z = $woman->calc2();
print “Student show2 = $z \n”;
}
##############
1;

 

実行ファイル名:test1.pl

use strict;
use Data::Dumper;
use Student;my $stu = Student->new();
$stu->get( 1 ,2 );
$stu->show( );
$stu->show2(10,20 );

実行結果:

>perl test1.plStudent show = 3
Student show2 = 30