=encoding euc-jp =head1 NAME X X =begin original perlobj - Perl objects =end original perlobj - Perl のオブジェクト =head1 DESCRIPTION =begin original First you need to understand what references are in Perl. See L for that. Second, if you still find the following reference work too complicated, a tutorial on object-oriented programming in Perl can be found in L and L. =end original まず最初に、あなたが Perl におけるリファレンスがなんであるかを理解している 必要があります。 L を参照してください。 第二に、これから説明するリファレンスの動作が複雑すぎると思うようなら、 Perl におけるオブジェクト指向プログラミングのチュートリアルが L と L にあります。 =begin original If you're still with us, then here are three very simple definitions that you should find reassuring. =end original ここまででまだ読み進める気があるのなら、あなたを安心させるだろう 三つの非常に単純な定義があります。 =over 4 =item 1. =begin original An object is simply a reference that happens to know which class it belongs to. =end original オブジェクトとは、単に自分がどのクラスに属しているのかを 知っているようなリファレンスです。 =item 2. =begin original A class is simply a package that happens to provide methods to deal with object references. =end original クラスとは、単にオブジェクトのリファレンスを取り扱うメソッドを 提供するパッケージです。 =item 3. =begin original A method is simply a subroutine that expects an object reference (or a package name, for class methods) as the first argument. =end original メソッドとは、単にその第一引数にオブジェクトのリファレンス (もしくはクラスのメソッドに対するパッケージ名)を取るような サブルーチンです。 =back =begin original We'll cover these points now in more depth. =end original これらのポイントを、より深く掘り下げて行きます。 =head2 An Object is Simply a Reference X X X X (オブジェクトは単なるリファレンス) =begin original Unlike say C++, Perl doesn't provide any special syntax for constructors. A constructor is merely a subroutine that returns a reference to something "blessed" into a class, generally the class that the subroutine is defined in. Here is a typical constructor: =end original C++ とは違って、Perl はコンストラクタに対して特別な構文を用意していません。 コンストラクタは単に、クラスに "bless" したなにかのリファレンスを 返すようなサブルーチンで、一般的にはサブルーチンが定義されているクラスです。 以下に典型的なコンストラクタを示します。 package Critter; sub new { bless {} } =begin original That word C isn't special. You could have written a construct this way, too: =end original C という語は特別なものではありません。 コンストラクタを以下のように記述することもできます: package Critter; sub spawn { bless {} } =begin original This might even be preferable, because the C++ programmers won't be tricked into thinking that C works in Perl as it does in C++. It doesn't. We recommend that you name your constructors whatever makes sense in the context of the problem you're solving. For example, constructors in the Tk extension to Perl are named after the widgets they create. =end original 実際のところ、これは C++ プログラマーが C++ と同じように Perl の C が動くと考えて落とし穴にはまることがないという点で 好ましいものではあります。 あなたには、あなたが解決しようとしている問題に関するコンテキスト でわかりやすいコンストラクタにすることをお奨めします。 例を挙げると、Perl の Tk エクステンションのコンストラクタでは、 作成するウィジェットから名前を取っています。 =begin original One thing that's different about Perl constructors compared with those in C++ is that in Perl, they have to allocate their own memory. (The other things is that they don't automatically call overridden base-class constructors.) The C<{}> allocates an anonymous hash containing no key/value pairs, and returns it The bless() takes that reference and tells the object it references that it's now a Critter, and returns the reference. This is for convenience, because the referenced object itself knows that it has been blessed, and the reference to it could have been returned directly, like this: =end original Perl のコンストラクタに関して C++ と違うことは、 C++ では自分でメモリを割り当てる必要があるということです。 C<{}> は空の無名ハッシュを割り当てます。 bless() は引数にリファレンスを取り、そのオブジェクトにオブジェクトが Critter のリファレンスであることを教え、リファレンスを返します。 参照されているオブジェクトはそれ自身自分が bless されていることを知っていて、 リファレンスは以下の例のように直接返すことができます。 sub new { my $self = {}; bless $self; return $self; } =begin original You often see such a thing in more complicated constructors that wish to call methods in the class as part of the construction: =end original 実際のところ、構築の一部としてクラスのメソッドを呼び出すようなもっと 複雑なコンストラクタを良く見かけることでしょう。 sub new { my $self = {}; bless $self; $self->initialize(); return $self; } =begin original If you care about inheritance (and you should; see L), then you want to use the two-arg form of bless so that your constructors may be inherited: =end original 継承について心配していて(そうあるべきなのですが。 Lを参照してください)、 継承されているかもしれないコンストラクタで引数二つを取る形式の bless を 使いたいのであれば: sub new { my $class = shift; my $self = {}; bless $self, $class; $self->initialize(); return $self; } =begin original Or if you expect people to call not just C<< CLASS->new() >> but also C<< $obj->new() >>, then use something like the following. (Note that using this to call new() on an instance does not automatically perform any copying. If you want a shallow or deep copy of an object, you'll have to specifically allow for that.) The initialize() method used will be of whatever $class we blessed the object into: =end original あるいは、ユーザーが C<< CLASS->new() >> ではなく C<< $obj->new() >> を使うことを期待しているのであれば、以下のような形式を使います。 (インスタンスに対して new() を呼び出すのにこれを使っても、自動的なコピーは 一切行われないことに注意してください。 もしオブジェクトに対して浅い、あるいは深いコピーを望むなら、それが できるように特に処理しなければならないでしょう。) initialize() というメソッドは $class を私たちがオブジェクトに bless しているかどうかに関らず使われます。 sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self, $class; $self->initialize(); return $self; } =begin original Within the class package, the methods will typically deal with the reference as an ordinary reference. Outside the class package, the reference is generally treated as an opaque value that may be accessed only through the class's methods. =end original クラスパッケージの中では、メソッドはリファレンスを普通のリファレンスとして 扱うでしょう。 クラスパッケージの外側では、リファレンスは一般的にクラスメソッドを 通してのみアクセスすることのできる不透明な値(opaque value)であるかのように 扱われます。 =begin original Although a constructor can in theory re-bless a referenced object currently belonging to another class, this is almost certainly going to get you into trouble. The new class is responsible for all cleanup later. The previous blessing is forgotten, as an object may belong to only one class at a time. (Although of course it's free to inherit methods from many classes.) If you find yourself having to do this, the parent class is probably misbehaving, though. =end original コンストラクタは現在参照されているオブジェクトを別のクラスに 属させるために、再 bless するかもしれません; これはほとんど確実にトラブルに巻き込まれます。 しかし、その新しいクラスは、後で掃除する原因となります。 オブジェクトは一度に一つのクラスにしか属することができないかのように 以前の bless は忘れ去られます(多くのクラスからメソッドを継承することが 自由にできるとしても、です)。 もし再ブレスしなければならないというのなら、その親クラスは不正な 振る舞いをしています。 =begin original A clarification: Perl objects are blessed. References are not. Objects know which package they belong to. References do not. The bless() function uses the reference to find the object. Consider the following example: =end original 解説: Perl のオブジェクトは bless されています。 リファレンスはそうではありません。 オブジェクトは自分が属しているパッケージがなんであるか知っていますが、 リファレンスは知りません。 関数 bless() はリファレンスをオブジェクトとみなすために使われます。 以下の例を見てください。 $a = {}; $b = $a; bless $a, BLAH; print "\$b is a ", ref($b), "\n"; =begin original This reports $b as being a BLAH, so obviously bless() operated on the object and not on the reference. =end original これは "$b as being a BLAH" と表示されます; これで明らかなように、bless() はリファレンスに対してではなく オブジェクトに作用します。 =head2 A Class is Simply a Package X X X<@ISA> X (クラスは単なるパッケージ) =begin original Unlike say C++, Perl doesn't provide any special syntax for class definitions. You use a package as a class by putting method definitions into the class. =end original C++ とは異なり、Perl はクラス定義に対する特別な構文を用意してはいません。 パッケージを、メソッド定義を押し込められたクラスとして使います。 =begin original There is a special array within each package called @ISA, which says where else to look for a method if you can't find it in the current package. This is how Perl implements inheritance. Each element of the @ISA array is just the name of another package that happens to be a class package. The classes are searched for missing methods in depth-first, left-to-right order by default (see L for alternative search order and other in-depth information). The classes accessible through @ISA are known as base classes of the current class. =end original 各パッケージには、カレントのパッケージでメソッドを見つけられなかったときに メソッドを探しに行く別のパッケージを指示する @ISA と呼ばれる 特殊な配列があります。 これが、Perl が継承を実装しているやり方です。 配列 @ISA の各要素は、クラスパッケージである別のパッケージの名前です。 見つからないメソッドは、デフォルトでは深さ優先、左から右の順序でクラスを 探します。 (その他の検索順と、その他のより深い情報については L を 参照してください)。 @ISA を通じてでアクセスすることのできるクラスは、カレントクラスの 基底クラスとして知られています。 =begin original All classes implicitly inherit from class C as their last base class. Several commonly used methods are automatically supplied in the UNIVERSAL class; see L<"Default UNIVERSAL methods"> for more details. X X X =end original 全てのクラスは暗黙のうちにその基底クラスとして C という クラスを継承しています。 UNIVERSAL クラスで自動的に提供される一般的に使われるメソッドが いくつかあります。 詳しくは L<"Default UNIVERSAL methods"> を参照してください。 X X X =begin original If a missing method is found in a base class, it is cached in the current class for efficiency. Changing @ISA or defining new subroutines invalidates the cache and causes Perl to do the lookup again. =end original 基底クラスで探しているメソッドが見つかれば、効率のために そのメソッドはカレントクラスでキャッシングされます。 @ISA の変更や新たなサブルーチンの定義はキャッシュを無効化し、Perl に再度の 走査を行わせます。 =begin original If neither the current class, its named base classes, nor the UNIVERSAL class contains the requested method, these three places are searched all over again, this time looking for a method named AUTOLOAD(). If an AUTOLOAD is found, this method is called on behalf of the missing method, setting the package global $AUTOLOAD to be the fully qualified name of the method that was intended to be called. X =end original カレントクラス、名前つきの基底クラス、UNIVERSAL クラスを検索して、 これらのいずれもが要求されたメソッドを持っていなければ、 AUTOLOAD() という名前のメソッドを検索します。 AUTOLOAD が見つかれば、このメソッドは見失ったメソッドの途中で 呼び出され、パッケージグローバルの $AUTOLOAD をメソッドの完全修飾名に なるように設定します。 X =begin original If none of that works, Perl finally gives up and complains. =end original ここまで全部失敗したならば、Perl は音を上げてエラーメッセージを出します。 =begin original If you want to stop the AUTOLOAD inheritance say simply X =end original AUTOLOAD の継承を止めたい場合は、単に以下のようにすると: X sub AUTOLOAD; =begin original and the call will die using the name of the sub being called. =end original 呼び出しは予備されたサブルーチンの名前を使って die します。 =begin original Perl classes do method inheritance only. Data inheritance is left up to the class itself. By and large, this is not a problem in Perl, because most classes model the attributes of their object using an anonymous hash, which serves as its own little namespace to be carved up by the various classes that might want to do something with the object. The only problem with this is that you can't sure that you aren't using a piece of the hash that isn't already used. A reasonable workaround is to prepend your fieldname in the hash with the package name. X X =end original Perl のクラスはメソッドの継承のみを行います。 データの継承はクラス自身にまかされています。 このことは Perl の問題ではありません。 なぜなら、大部分のクラスは無名ハッシュを使って、クラスのオブジェクトの 属性をモデル化しています。 この無名ハッシュはそのオブジェクトに対して何事かを行うような 様々なクラス毎に固有の名前空間を小さくきり分ける役割を果たします。 これに関する問題はあなたが使ったハッシュのひとかけらが 既に使われたものではないということに確信が持てないことです。 これに関する現実的な対応策は、ハッシュのフィールド名に パッケージ名を使うというものです。 X X sub bump { my $self = shift; $self->{ __PACKAGE__ . ".count"}++; } =head2 A Method is Simply a Subroutine X (メソッドは単なるサブルーチン) =begin original Unlike say C++, Perl doesn't provide any special syntax for method definition. (It does provide a little syntax for method invocation though. More on that later.) A method expects its first argument to be the object (reference) or package (string) it is being invoked on. There are two ways of calling methods, which we'll call class methods and instance methods. =end original C++ とは異なり、Perl はメソッド定義に対する特別な構文を持っていません (しかしながら、後述するようにメソッドの起動のためにはちょっとした 構文を提供しています)。 メソッドはその第一引数として、そのメソッドを起動したオブジェクト (リファレンス)、もしくはパッケージ(文字列)を期待しています。 メソッドの呼び出し方にはには二種類あり、 それぞれ私たちがクラスメソッド、インスタンスメソッドと呼ぶものです。 =begin original A class method expects a class name as the first argument. It provides functionality for the class as a whole, not for any individual object belonging to the class. Constructors are often class methods, but see L and L for alternatives. Many class methods simply ignore their first argument, because they already know what package they're in and don't care what package they were invoked via. (These aren't necessarily the same, because class methods follow the inheritance tree just like ordinary instance methods.) Another typical use for class methods is to look up an object by name: =end original クラスメソッドは、その第一引数としてクラスの名前を期待します。 クラスメソッドはクラス全体に対する機能を提供するものであって、クラスに 属する個々のオブジェクトに対するものではありません。 コンストラクタは普通はクラスメソッドですが、 代替案については L と L を参照してください。 多くのクラスメソッドは単純にその第一引数を無視します。 これは、既に自分が置かれているパッケージの名前を知っているし、 パッケージがどのような経路で起動されたのかを 気にする必要がないからです。 (通常のインスタンスメソッドと同じようにクラスメソッドは継承木に 従っているので、これらが同一である必要はありません)クラスメソッドの もう一つの典型的な使用例は名前によってオブジェクトを 検査するためのものです。 sub find { my ($class, $name) = @_; $objtable{$name}; } =begin original An instance method expects an object reference as its first argument. Typically it shifts the first argument into a "self" or "this" variable, and then uses that as an ordinary reference. =end original インスタンスメソッドは、その第一引数としてオブジェクトのリファレンスを 期待します。 典型的には、第一引数は "self" とか "this" といった変数に shift され、 以後は通常のリファレンスのように扱います。 sub display { my $self = shift; my @keys = @_ ? @_ : sort keys %$self; foreach $key (@keys) { print "\t$key => $self->{$key}\n"; } } =head2 Method Invocation X X X X<< -> >> (メソッドの起動) =begin original For various historical and other reasons, Perl offers two equivalent ways to write a method call. The simpler and more common way is to use the arrow notation: =end original 歴史的、あるいはその他の様々な理由によって、Perl はメソッド呼び出しを 書くための、二つの等価な方法を提供しています。 より単純でより一般的な方法は矢印記法を使うことです: my $fred = Critter->find("Fred"); $fred->display("Height", "Weight"); =begin original You should already be familiar with the use of the C<< -> >> operator with references. In fact, since C<$fred> above is a reference to an object, you could think of the method call as just another form of dereferencing. =end original リファレンスに対する C<< -> >> 演算子の使用については既に 親しんでいることでしょう。 実際のところ、上述の C<$fred> はオブジェクトへのリファレンスなので、 メソッド呼び出しを、単にデリファレンスの別の形と考えることができます。 =begin original Whatever is on the left side of the arrow, whether a reference or a class name, is passed to the method subroutine as its first argument. So the above code is mostly equivalent to: =end original 矢印の左側に何があるか、リファレンスかクラス名か、は最初の引数として メソッドサブルーチンに渡されます。 従って、上述のコードは以下のものとほとんど等価です: my $fred = Critter::find("Critter", "Fred"); Critter::display($fred, "Height", "Weight"); =begin original How does Perl know which package the subroutine is in? By looking at the left side of the arrow, which must be either a package name or a reference to an object, i.e. something that has been blessed to a package. Either way, that's the package where Perl starts looking. If that package has no subroutine with that name, Perl starts looking for it in any base classes of that package, and so on. =end original サブルーチンがどのパッケージにあるかを Perl はどうやって知るのでしょうか? 矢印の左側を見ます; これはパッケージ名かオブジェクトへのリファレンス (つまりパッケージに bless された何か) のどちらかである必要があります。 どちらの場合も、それが Perl が探し始めるパッケージです。 もしそのパッケージに指定された名前のサブルーチンがないなら、Perl は そのパッケージの基底クラスを探し始めます; それを繰り返します。 =begin original If you need to, you I force Perl to start looking in some other package: =end original もし必要なら、Perl に他のパッケージを見るように強制することも I<可能です>。 my $barney = MyCritter->Critter::find("Barney"); $barney->Critter::display("Height", "Weight"); =begin original Here C is presumably a subclass of C that defines its own versions of find() and display(). We haven't specified what those methods do, but that doesn't matter above since we've forced Perl to start looking for the subroutines in C. =end original ここで C は、おそらく自分自身の find() と display() を 定義しているC のサブクラスです。 これらのメソッドが何をしているかは指定していませんが、 これらのサブルーチンを C から探すように Perl に強制しているので、 それは問題になりません。 =begin original As a special case of the above, you may use the C pseudo-class to tell Perl to start looking for the method in the packages named in the current class's C<@ISA> list. X =end original 上記の特別な場合として、現在のクラスの C<@ISA> リストにあるパッケージから メソッドを探し始めるように Perl に指示する、C 擬似クラスもあります。 X package MyCritter; use base 'Critter'; # sets @MyCritter::ISA = ('Critter'); sub display { my ($self, @args) = @_; $self->SUPER::display("Name", @args); } =begin original It is important to note that C refers to the superclass(es) of the I and not to the superclass(es) of the object. Also, the C pseudo-class can only currently be used as a modifier to a method name, but not in any of the other ways that class names are normally used, eg: X =end original C は、オブジェクトのスーパークラスではなく、I<カレントパッケージ> の スーパークラスを参照するということに注意することは重要です。 また C 擬似クラスは現在のところメソッド名への修飾子としてのみ 使え、普通に使われるクラス名のその他の方法は使えません。 つまり: X something->SUPER::method(...); # OK SUPER::method(...); # WRONG SUPER->method(...); # WRONG =begin original Instead of a class name or an object reference, you can also use any expression that returns either of those on the left side of the arrow. So the following statement is valid: =end original クラス名やオブジェクトリファレンスの代わりに、矢印の左側に 置けるもののどちらかを返す任意の式も使えます。 従って、以下の文は有効です: Critter->find("Fred")->display("Height", "Weight"); =begin original and so is the following: =end original そして以下のようにします: my $fred = (reverse "rettirC")->find(reverse "derF"); =begin original The right side of the arrow typically is the method name, but a simple scalar variable containing either the method name or a subroutine reference can also be used. =end original 矢印の右側は典型的にはメソッド名ですが、メソッド名やサブルーチン リファレンスが入った単純スカラ変数も使えます。 =head2 Indirect Object Syntax X X X (間接オブジェクト構文) =begin original The other way to invoke a method is by using the so-called "indirect object" notation. This syntax was available in Perl 4 long before objects were introduced, and is still used with filehandles like this: =end original メソッドを起動する他の方法は、「間接オブジェクト」記法と呼ばれる方法を 使うものです。 この文法は、オブジェクトが導入されるよりずっと以前の Perl 4 から 利用可能で、以下のように、ファイルハンドルで今でも使われています: print STDERR "help!!!\n"; =begin original The same syntax can be used to call either object or class methods. =end original これと同じ構文を、クラスメソッドやインスタンスメソッドを呼び出すときに 使うことができます。 my $fred = find Critter "Fred"; display $fred "Height", "Weight"; =begin original Notice that there is no comma between the object or class name and the parameters. This is how Perl can tell you want an indirect method call instead of an ordinary subroutine call. =end original オブジェクトやクラス名とパラメータの間にカンマがないことに 注目してください。 これによって、通常のサブルーチン呼び出しではなく間接メソッド呼び出しを しようとしていることを Perl に伝えています。 =begin original But what if there are no arguments? In that case, Perl must guess what you want. Even worse, it must make that guess I. Usually Perl gets it right, but when it doesn't you get a function call compiled as a method, or vice versa. This can introduce subtle bugs that are hard to detect. =end original しかし、引数がなかったら? この場合、Perl は求められているものを推測しなければなりません。 さらに悪いことに、この推測は B<コンパイル時> に行わなければなりません。 Perl は通常正しい答を得るのですが、そうでなかった場合、あなたはメソッドとして 関数呼び出しがコンパイルされたものを受け取ります。 これは検出が非常に困難なバグとなり得るものです。 =begin original For example, a call to a method C in indirect notation -- as C++ programmers are wont to make -- can be miscompiled into a subroutine call if there's already a C function in scope. You'd end up calling the current package's C as a subroutine, rather than the desired class's method. The compiler tries to cheat by remembering bareword Cs, but the grief when it messes up just isn't worth the years of debugging it will take you to track down such subtle bugs. =end original 例を挙げると、(C++ プログラマーがそうしたくなるような)C という メソッドの間接表記での呼び出しは、カレントのスコープですでに C 関数が あった場合には間違ったサブルーチン呼び出しにコンパイルされてしまいます。 結果として、望んでいたクラスメソッドではなく、カレントパッケージの C がサブルーチンとして呼び出されることになるのです。 コンパイラはこの問題を裸の単語の C を覚えておくことによって 避けようと試みますが、それが失敗してしまった場合にはデバッグするのが とても面倒な結果となってしまうことになるでしょう。 =begin original There is another problem with this syntax: the indirect object is limited to a name, a scalar variable, or a block, because it would have to do too much lookahead otherwise, just like any other postfix dereference in the language. (These are the same quirky rules as are used for the filehandle slot in functions like C and C.) This can lead to horribly confusing precedence problems, as in these next two lines: =end original この文法にも問題があります: 間接オブジェクトは名前、スカラ変数、 ブロックに限定されます; なぜなら、他の言語における 接尾辞デリファレンスと同様に、多すぎる先読みをする必要があるからです (これらは C や C のような関数におけるファイルハンドルスロットと 同様な奇妙なルールです)。 これは次に挙げる例のように、混乱した優先順位問題を 導くことになります。 move $obj->{FIELD}; # probably wrong! move $ary[$i]; # probably wrong! =begin original Those actually parse as the very surprising: =end original これらはなんと以下のように解釈されるのです: $obj->move->{FIELD}; # Well, lookee here $ary->move([$i]); # Didn't expect this one, eh? =begin original Rather than what you might have expected: =end original あなたが期待したのはこうでしょう: $obj->{FIELD}->move(); # You should be so lucky. $ary[$i]->move; # Yeah, sure. =begin original To get the correct behavior with indirect object syntax, you would have to use a block around the indirect object: =end original 間接オブジェクト構文の正しい振る舞いを得るためには、間接オブジェクトの周りに ブロックを使う必要があるかもしれません: move {$obj->{FIELD}}; move {$ary[$i]}; =begin original Even then, you still have the same potential problem if there happens to be a function named C in the current package. B >> notation suffers from neither of these disturbing ambiguities, so we recommend you use it exclusively.> However, you may still end up having to read code using the indirect object notation, so it's important to be familiar with it. =end original この場合でも、もし現在のパッケージにたまたま C という名前の関数が あると、同じ潜在的問題があります。 B >> 記法はこれらの物騒なあいまいさのどちらの影響も受けないので、 これだけを使うことを勧めます。> しかし、結局は間接オブジェクト記法を使ったコードを読む必要が あるかもしれないので、この記法に親しんでおくことが重要です。 =head2 Default UNIVERSAL methods X (デフォルトの UNIVERSAL メソッド) =begin original The C package automatically contains the following methods that are inherited by all other classes: =end original C パッケージには、他の全てのクラスが自動的に継承する 以下のようなメソッドがあります。 =over 4 =item isa(CLASS) X =begin original C returns I if its object is blessed into a subclass of C =end original C は、オブジェクトが C のサブクラスに bless されていれば I を返します。 =begin original You can also call C as a subroutine with two arguments. Of course, this will do the wrong thing if someone has overridden C in a class, so don't do it. =end original C を、2 引数を持つサブルーチンとして呼び出すこともできます。 もちろん、もし誰かがクラスの中で C をオーバーライドしていると 良くないことになるので、これをしてはいけません。 =begin original If you need to determine whether you've received a valid invocant, use the C function from L: X X =end original もし、有効な呼び出し元を受け取っているかどうかを決定する必要があるなら、 L の C を使ってください: X X if (blessed($ref) && $ref->isa( 'Some::Class')) { # ... } =begin original C returns the name of the package the argument has been blessed into, or C. =end original C は、引数が bless されているパッケージ名か、あるいはC を 返します。 =item can(METHOD) X =begin original C checks to see if its object has a method called C, if it does then a reference to the sub is returned, if it does not then I is returned. =end original C はオブジェクトが C というメソッドを持っているかどうかを検査し、 持っていればそのサブルーチンに対するリファレンスを返し、持っていなければ I を返します。 =begin original C can also be called as a subroutine with two arguments. It'll always return I if its first argument isn't an object or a class name. The same caveats for calling C directly apply here, too. =end original C を、2 引数を持つサブルーチンとして呼び出すこともできます。 もし 1 つめの引数がオブジェクトかクラス名でなかった場合、常に I を C を直接呼び出す場合と同じ問題点もあります。 =item VERSION( [NEED] ) X =begin original C returns the version number of the class (package). If the NEED argument is given then it will check that the current version (as defined by the $VERSION variable in the given package) not less than NEED; it will die if this is not the case. This method is normally called as a class method. This method is called automatically by the C form of C. =end original C はクラス(パッケージ)のバージョン番号を返します。 引数 NEED が与えられている場合、カレントバージョン(指定されたパッケージ 変数 $VERSION で定義されます)が NEED よりも小さくないことを検査します。 もし小さければ die します。 このメソッドは通常クラスメソッドとして呼び出されます。 また、このメソッドは C の C 形式によって自動的に呼び出されます。 use A 1.2 qw(some imported subs); # implies: A->VERSION(1.2); =back =begin original B C directly uses Perl's internal code for method lookup, and C uses a very similar method and cache-ing strategy. This may cause strange effects if the Perl code dynamically changes @ISA in any package. =end original B<注意:> C は Perl の内部コードをメソッドの検索のために使用し、 Cはそれと良く似た手法と、キャッシングを行います。 これにより、@ISA をパッケージの中で動的に変更したりすると、奇妙な影響を 引き起こす可能性があります。 =begin original You may add other methods to the UNIVERSAL class via Perl or XS code. You do not need to C to make these methods available to your program (and you should not do so). =end original Perl プログラムや XS プログラムを通じて、UNIVERSAL クラスに他のメソッドを 追加することもできます。 追加したメソッドを自作のプログラムで使えるようにするために C を行う必要はありません (そしてそうするべきではありません)。 =head2 Destructors X X (デストラクタ) =begin original When the last reference to an object goes away, the object is automatically destroyed. (This may even be after you exit, if you've stored references in global variables.) If you want to capture control just before the object is freed, you may define a DESTROY method in your class. It will automatically be called at the appropriate moment, and you can do any extra cleanup you need to do. Perl passes a reference to the object under destruction as the first (and only) argument. Beware that the reference is a read-only value, and cannot be modified by manipulating C<$_[0]> within the destructor. The object itself (i.e. the thingy the reference points to, namely C<${$_[0]}>, C<@{$_[0]}>, C<%{$_[0]}> etc.) is not similarly constrained. =end original あるオブジェクトに対する最後のリファレンスが消滅したとき、そのオブジェクトは 自動的に破棄されます(これはあなたがリファレンスを大域変数に格納していて、 プログラムを終了するときでもそうです)。 もしオブジェクトが解放される直前に制御を横取りしたいのであれば、クラスの 中で DESTROY メソッドを定義することができます。 このメソッドは適切な時期に自動的に呼び出され、あなたが必要とする クリーンアップを行うことができます。 デストラクトされるオブジェクトに対する第一引数(かつ唯一の引数)として リファレンスを渡します。 このリファレンスは読み込み専用の値であり、デストラクタの中で C<$_[0]> を操作することによって変更することはできません。 オブジェクトそれ自身(C<${$_[0]}>, C<@{$_[0]}>, C<%{$_[0]}> のような名前の ついたものに対するリファレンス)は同様に強制されません。 =begin original Since DESTROY methods can be called at unpredictable times, it is important that you localise any global variables that the method may update. In particular, localise C<$@> if you use C and localise C<$?> if you use C or backticks. =end original DESTROY メソッドは予測不能な回数呼び出されるかもしれないので、 メソッドが更新する全てのグローバル変数をローカル化することが重要です。 特に、C を使うなら C<$@> を、C や逆クォートを使うなら C<$?> をローカル化してください。 =begin original If you arrange to re-bless the reference before the destructor returns, perl will again call the DESTROY method for the re-blessed object after the current one returns. This can be used for clean delegation of object destruction, or for ensuring that destructors in the base classes of your choosing get called. Explicitly calling DESTROY is also possible, but is usually never needed. =end original デストラクタから抜ける前にリファレンスを再 bless するようにアレンジすると、 perl はカレントのデストラクタから呼び出した後で再 bless されたオブジェクトの ための DESTROY メソッドを再度呼び出します。 これはオブジェクトの委譲を始末するのに使ったり、あなたが呼び出すことを 選択した基底クラスのデストラクタを保証するのに使うことができます。 陽に DESTROY を呼び出すことも可能ですが、通常はそうする必要はありません。 =begin original Do not confuse the previous discussion with how objects I in the current one are destroyed. Such objects will be freed and destroyed automatically when the current object is freed, provided no other references to them exist elsewhere. =end original カレントで破棄されるオブジェクトに属するオブジェクトに関して 混乱しないようにしてください。 そのようなオブジェクトはカレントオブジェクトが解放されるときに自動的に 解放・破棄が行われ、他のなにものに対するリファレンスがないようにします。 =head2 Summary (まとめ) =begin original That's about all there is to it. Now you need just to go off and buy a book about object-oriented design methodology, and bang your forehead with it for the next six months or so. =end original これで、ここでなすべきことは全て終わりました。 今、あなたは部屋を出てオブジェクト指向方法論に関する書籍を購入して、 そして六ヶ月かそこらの間悩む必要があるでしょう。 =head2 Two-Phased Garbage Collection X X X X X X (2 フェーズガベージコレクション) =begin original For most purposes, Perl uses a fast and simple, reference-based garbage collection system. That means there's an extra dereference going on at some level, so if you haven't built your Perl executable using your C compiler's C<-O> flag, performance will suffer. If you I built Perl with C, then this probably won't matter. =end original ほとんどの目的のために、Perl は単純かつ高速なリファレンスベースの ガベージコレクションシステムを使用します。 このため、幾つかの段階において余計なデリファレンスが起こり、使用している Perl を ビルドするときに C<-O> フラグをコンパイラに使っていなければ、性能が劣化します。 Perl をビルドするときに C を使っていれば、このデリファレンスは問題とは ならないでしょう。 =begin original A more serious concern is that unreachable memory with a non-zero reference count will not normally get freed. Therefore, this is a bad idea: =end original より深刻な問題は、ゼロでないリファレンスカウントを持っている アクセスできないメモリー(unreachable memory)が通常は 解放されないということです。 したがって、以下のようにすることは悪いアイデアです。 { my $a; $a = \$a; } =begin original Even thought $a I go away, it can't. When building recursive data structures, you'll have to break the self-reference yourself explicitly if you don't care to leak. For example, here's a self-referential node such as one might use in a sophisticated tree structure: =end original $a が無くなるように思えるのですが、できないのです。 再帰的データ構造を構築したとき、メモリリークを気にしないためには自分自身で、 明示的に、自己参照を壊さなければなりません。 たとえば、木構造を扱うときに使うような自己参照構造体として以下のようなものを 考えてみます。 sub new_node { my $class = shift; my $node = {}; $node->{LEFT} = $node->{RIGHT} = $node; $node->{DATA} = [ @_ ]; return bless $node => $class; } =begin original If you create nodes like that, they (currently) won't go away unless you break their self reference yourself. (In other words, this is not to be construed as a feature, and you shouldn't depend on it.) =end original このようなノードを生成するとき、あなた自身が自分で自己参照を壊さない 限りノードはなくなりません(言い換えれば、これは仕様として 解釈されるものではなく、これに依存すべきではないということです)。 =begin original Almost. =end original もう一息。 =begin original When an interpreter thread finally shuts down (usually when your program exits), then a rather costly but complete mark-and-sweep style of garbage collection is performed, and everything allocated by that thread gets destroyed. This is essential to support Perl as an embedded or a multithreadable language. For example, this program demonstrates Perl's two-phased garbage collection: =end original インタプリタのスレッドが最終的にシャットダウンするとき(通常は プログラムを終了するとき)、コストが掛かりますが、完全な mark-and-sweep 形式のガベージコレクションが実行されます。 そして、(シャットダウンされる)スレッドによって割り当てられたすべての ものは破棄されます。 これはPerlを組み込みに使えるようにしたり、マルチスレッドに対応できる言語と するために重要なことです。 たとえば以下のプログラムは Perl の 2 フェーズガベージコレクションを デモンストレーションします。 #!/usr/bin/perl package Subtle; sub new { my $test; $test = \$test; warn "CREATING " . \$test; return bless \$test; } sub DESTROY { my $self = shift; warn "DESTROYING $self"; } package main; warn "starting program"; { my $a = Subtle->new; my $b = Subtle->new; $$a = 0; # break selfref warn "leaving block"; } warn "just exited block"; warn "time to die..."; exit; =begin original When run as F, the following output is produced: =end original F として実行したとき、以下のような出力をします。 starting program at /foo/test line 18. CREATING SCALAR(0x8e5b8) at /foo/test line 7. CREATING SCALAR(0x8e57c) at /foo/test line 7. leaving block at /foo/test line 23. DESTROYING Subtle=SCALAR(0x8e5b8) at /foo/test line 13. just exited block at /foo/test line 26. time to die... at /foo/test line 27. DESTROYING Subtle=SCALAR(0x8e57c) during global destruction. =begin original Notice that "global destruction" bit there? That's the thread garbage collector reaching the unreachable. =end original "global destruction" がどこにあるかわかりますか? これは、スレッド ガベージコレクタがアクセスできないオブジェクトに到達したということです。 =begin original Objects are always destructed, even when regular refs aren't. Objects are destructed in a separate pass before ordinary refs just to prevent object destructors from using refs that have been themselves destructed. Plain refs are only garbage-collected if the destruct level is greater than 0. You can test the higher levels of global destruction by setting the PERL_DESTRUCT_LEVEL environment variable, presuming C<-DDEBUGGING> was enabled during perl build time. See L for more information. =end original オブジェクトは常に破棄されます。 一般のリファレンス(regulaer refs)が破棄されなかった場合でもそうですし、 一般のリファレンスが分割されたパスで破棄された場合でさえ、 通常のリファレンス(ordinary refs)がオブジェクトデストラクタが自分自身を 破棄してしまったリファレンスを使うのを防ごうとする前に破棄されます。 plain なリファレンスは、そのデストラクトレベルが 0 以上であるときには ガベージコレクションのみ行なわれます。 Perl をビルドするときに C<-DDEBUGGING> が有効になっていれば、 PERL_DESTRUCT_LEVEL という環境変数に対する設定をすることによって、 グローバルデストラクションのレベルを検査することができます。 さらなる情報については L を参照してください。 =begin original A more complete garbage collection strategy will be implemented at a future date. =end original より完璧なガベージコレクションの戦略は将来実装されるでしょう。 =begin original In the meantime, the best solution is to create a non-recursive container class that holds a pointer to the self-referential data structure. Define a DESTROY method for the containing object's class that manually breaks the circularities in the self-referential structure. =end original 方法として最善なものは、自己再帰的なデータ構造に対するポインタを 保持するような非再帰的なコンテナクラスを作成することです。 そういったオブジェクトのクラスでの DESTORY メソッドの定義は 自己参照構造中の循環を手作業で断ち切るようなものになります。 =head1 SEE ALSO =begin original A kinder, gentler tutorial on object-oriented programming in Perl can be found in L, L and L. You should also check out L for other object tricks, traps, and tips, as well as L for some style guides on constructing both modules and classes. =end original Perl におけるオブジェクト指向プログラムに関するより親切で丁寧な チュートリアルは L, L, L にあります。 また、その他のオブジェクトの罠や小技については L を、 モジュールとクラスの作成に関するスタイルガイドについては L を 参照してください。 =begin meta Translate: KIMURA Koichi Update: Kentaro Shirakata (5.8.8-) =end meta