blessのタイミング

イニシャライズ中に他のメソッドを呼ぼうとしたら
Can't call method "hoge" on unblessed reference at ....
ってエラーが出た。しばらく悩む。

package Human;
sub new {
  my $class = shift;
  my $name = shift;
  my $age  = shift;
  my $self = {};
  $self->{name} = $name;
  $self->{age}  = $age;
  
  # hogeを呼びたいけど、
  # $selfはまだHumanのインスタンスじゃないからエラーになるらしい。
  $self->hoge();
  
  return bless $self, $class;
}

sub hoge{
  my $self = shift;
  print "I am ". $self->{name} .", Age is ". $self->{age} ."\n";
}


package main;
my $human = Human->new("Sato", 20);
....

↓こうしたら解決した。

package Human;
sub new {
  my $class = shift;
  my $name = shift;
  my $age  = shift;
  my $self = {};
  $self->{name} = $name;
  $self->{age}  = $age;
  
  # blessする。$selfがHumanのインスタンスになる。
  my $bless = bless $self, $class;
  
  # hogeを呼べる。
  $self->hoge();
  
  return $bless;
}

sub hoge{
  my $self = shift;
  print "I am ". $self->{name} .", Age is ". $self->{age} ."\n";
}


package main;
my $human = Human->new("Sato", 20);
....


ちょっと書かないとすぐ忘れる。。