2024/02/13 22:13:39

Perl 標準関数: bless

bless

bless REF,CLASSNAME

bless REF

This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is omitted, the current package is used. Because a "bless" is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if the function doing the blessing might be inherited by a derived class. See perltoot and perlobj for more about the blessing (and blessings) of objects.

Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names, so to prevent confusion, you may wish to avoid such package names as well. Make sure that CLASSNAME is a true value.

See "Perl Modules" in perlmod.

bless 関数は、リファレンスとクラス名を引数として、そのリファレンスをクラスのオブジェクトにします。 クラス名が省略された場合は、現在のパッケージが使用されます。 bless 関数は、コンストラクタの最後でリファレンスを返します。

bless 関数については、perltoot や perlobj を参照してください。また、perlmod も見てください。

bless サンプルコード

package Sample::Class;
use warnings;
use strict;

sub new {
    my $class = shift;
    my $arg   = shift;

    return bless $arg, $class;
}

bless よもやま

bless 関数は、オブジェクト指向プログラミングを知らない場合、ややとっつきにくいところがあるかもしれません。なぜなら、bless はオブジェクト指向プログラミングを Perl で行うために、リファレンスとクラスをひも付けるという関数だからです。 さっぱり意味がわからないなら、具体例をたくさんみると合点がいくかもしれません。CPAN モジュールのソースを漁れば、コンストラクタ(たいていは new メソッド)に bless 関数を見つけることができます。 また、普通のリファレンスと、blessed REF をダンプしてみれば、両者の違いがわかるかもしれません。

サイト内検索