#navi_header|Perl| PerlでのOOPの基本。 + "new"という名前のサブルーチンを持つパッケージを用意する。 ++ "new"はbless()された適当なリファレンスを返す。 + インスタンスメソッドとして使うサブルーチンは第一引数にbless()されたリファレンスを取る。 + 継承を行うには、パッケージの::ISAに継承したいパッケージ名のリストを指定する。 + 継承元のインスタンスメソッドを呼びたい場合は、SUPERを使う。 #code|perl|> #!/usr/bin/perl use strict; use warnings; use Test::More qw(no_plan); # サンプルなので"no_plan"で手抜き。 { package Animal; sub new { my $class = shift; my $self = {}; print "in '$class' constructor...\n"; bless ($self, $class); return $self; } sub speak { my $class = shift; print "in '$class' speak method...\n"; print "a $class goes ", $class->sound, "!\n"; } } { package Mouse; @Mouse::ISA = qw(Animal); sub sound { "squeak" } sub speak { my $class = shift; #$class->Animal::speak($class); $class->SUPER::speak($class); print "[but you can barely hear it!]\n"; } } $main::obj = Mouse->new(); $main::obj->speak(); isa_ok($main::obj, 'Animal'); isa_ok($main::obj, 'Mouse'); isnt(UNIVERSAL::isa($main::obj, "Horse"), 0); can_ok($main::obj, qw(speak sound)); isnt(UNIVERSAL::can($main::obj, 'hoge'), 0); ||< 実行結果 #pre||> DOS> perl class01.pl in 'Mouse' constructor... in 'Mouse=HASH(0x284fd4)' speak method... a Mouse=HASH(0x284fd4) goes squeak! [but you can barely hear it!] ok 1 - The object isa Animal ok 2 - The object isa Mouse ok 3 ok 4 - Mouse->can(...) ok 5 1..5 ||< PerlでのOOPの基本原理は変わりませんが、より分かりやすい書き方をサポートする為のCPANの主流が時代と共に変わるので厄介です。 上に挙げたコードはあくまでも基本原理の中核部分で、一番簡単なサンプルです。 #navi_footer|Perl|