bless()を使ってオブジェクト指向プログラミング
親クラス
package MyClass;
sub new {
my $thing = shift;
my $class = ref $thing || $thing;
my $self = bless {@_} , $class;
$self->init() if $self->can('init');
$self;
}
our %default = ( name => 'anonymous' );
sub init {
my $self = shift;
$self->{$_} = $default{$_} for keys %default;
$self;
}
sub name {
my $self = shift;
$self->{name} = shift if @_;
return $self->{name};
}
子クラス
package MyClass::Sub;
our @ISA = qw/MyClass/;
our %default = ( 'name' => 'taro' );
sub init {
my $self = shift;
$self->SUPER::init();
$self->{$_} = $default{$_} for keys %default;
}
クラスを利用
#!/usr/local/bin/perl
my $obj = MyClass::Sub->new( name => 'jiro' );
print $obj->name, "\n";
$obj->name('saburo');
print $obj->name, "\n";