小池啓仁 ヒロヒト応援ブログ By はてな

小池啓仁(コイケヒロヒト)の動画など。

小池啓仁 ヒロヒト応援ブログ By はてな

Perlでのオブジェクトとは? blessとは?

Perlでのオブジェクトとは、bless(祝福)されたリファレンスです。
では、blessとは、リファレンスとクラス名を結び付けることです。


以下にblessした場合と、しない場合のサンプルソースを例示します。
blessしない場合は、リファレンスとクラス名が結び付いていないので、メソッド起動でエラーとなっています。

プログラムソース(.\tstobject.pl)

#!/usr/bin/perl
use strict;
use DateString::DateStringx;
use DateString::DateStringy;

my $datex = DateString::DateStringx->new();
print $datex, "\n";   # blessされたリファレンスが格納されている
print $datex->to_string, "\n";

my $datey = DateString::DateStringy->new();
print $datey, "\n";   # 単なるリファレンスが格納されている
print $datey->to_string, "\n";

blessしたリファレンスを返すクラス(.\DateString\DateStringx.pm)

package DateString::DateStringx;
use strict;
sub new {
    my $class = shift; # 第一引数は、クラス名が渡される。
    my $time = shift || time();
    return bless { time => $time }, $class; # blessしたリファレンスを返す。
}
sub to_string {
    my $self = shift;
    return scalar localtime $self->{time};
}
1;
__END__

blessしないリファレンスを返すクラス(.\DateString\DateStringy.pm)

package DateString::DateStringy;
use strict;
sub new {
    my $class = shift; # 第一引数は、クラス名が渡される。
    my $time = shift || time();
    return { time => $time } # blessしていないリファレンスを返す。
}
sub to_string {
    my $self = shift;
    return scalar localtime $self->{time};
}
1;
__END__

実行結果

C:\Documents and Settings\xxx>perl .\tstobject.pl
DateString::DateStringx=HASH(0x1625e50)
Thu Feb  7 20:41:06 2008
HASH(0x1625f28)
Can't call method "to_string" on unblessed reference at .\tstobject.pl line 14.