perlでOOP
perlでオブジェクト指向プログラミングをしているのだが、つまんないことで、1時間30分もハマった。
.... package Foo; sub new { my $class = shift; my $h = { 'title' => shift }; bless $h, $class; } sub title { my $self = shift; $self->{'title'}; } package Bar; sub new { my $class = shift; my $h = { 'title' => shift }; bless $h, $class; } sub foo { my $o = shift; $o->title; } package main; $o = Foo->new("タイトルFoo"); $oo = Bar->new("タイトルBar"); print $o->title . "\n"; print $oo->foo($o) . "\n";
これで実行すると、
$ perl test.pl タイトルFoo Can't locate object method "title" via package "Bar" at test.pl line XX.
のような感じで怒られてしまう。
perlでは、メソッドへの引数には自分自身のインスタンスが渡されるのが特徴なのだが、それをなぜかすっかり見落としていた。そう、
my $o = shift;
を
my($self, $o) = @_;
としないとうまくいかないのだ。
あぁ、注意散漫というか、なんというか。時間がもったいなかった。
それにしても、
package Bar; sub new { my $class = shift; my $h = { 'title' => shift }; bless $h, $class; }
blessはないよなぁ。
bless REF,PACKAGE
この関数は、(REF で渡された) 参照されるオブジェクトに対し、PACKAGE 内のオブジェクトとなったことを伝えます。
お決まり事だと思えばいいのかもしれないけど、どうもね。