ことはじめ(2)
今日は継承の勉強です。bless関連がまだまだ理解しきれていません。コンストラクタの代わりに初期化メソッドを用意してしのいでみました。use vars qw($hoge); はC++でいうところのstaticフィールドのようです。またBEGIN節は一度しか呼ばれないようです。
Human.pm
package Object; use strict; use Data::Dumper; # staic フィールドの定義 use vars qw($counter); BEGIN { $counter = 0; } # インスタンスフィールドの定義 sub init { my $class = shift; my $self = {}; $counter++; print "called Object$counter()\n"; bless { _name => 'name', }, $class; } # コンストラクタ sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } # 名前を得る sub getName { my($this,@args) = @_; return $this->{_name}; } # 名前を設定する sub setName { my($this,@args) = @_; $this->{_name} = $args[0] if $args[0]; } # # Humanクラス # package Human; use base qw( Object ); # インスタンスフィールドの定義 sub init { Object->init(); print "called Human()\n"; bless { _age => 0, }, "Human"; } # 年齢を得る sub getAge { my($this,@args) = @_; return $this->{_age}; } # 年齢を設定する sub setAge { my($this,@args) = @_; $this->{_age} = $args[0] if $args[0]; } # # テストクラス # package main; my $human1 = Human->new()->init(); my $human2 = Human->new()->init(); $human1->setName("John"); $human1->setAge(30); $human2->setName("Mary"); $human2->setAge(25); print $human1->getName()."(".$human1->getAge().")\n"; print $human2->getName()."(".$human2->getAge().")\n";