=encoding euc-jp =for comment Consistent formatting of this file is achieved with: perl ./Porting/podtidy pod/perlobj.pod =head1 NAME X X =begin original perlobj - Perl object reference =end original perlobj - Perl オブジェクトのリファレンス =head1 DESCRIPTION =begin original This document provides a reference for Perl's object orientation features. If you're looking for an introduction to object-oriented programming in Perl, please see L. =end original この文書は、Perl のオブジェクト指向機能のリファレンスを提供します。 Perl でのオブジェクト指向プログラミングの概要を探しているなら、 L を参照してください。 =begin original In order to understand Perl objects, you first need to understand references in Perl. See L for details. =end original Perl のオブジェクトを理解するためには、まず Perl のリファレンスを 理解する必要があります。 詳しくは L を参照してください。 =begin original This document describes all of Perl's object-oriented (OO) features from the ground up. If you're just looking to write some object-oriented code of your own, you are probably better served by using one of the object systems from CPAN described in L. =end original この文書は Perl のオブジェクト指向 (OO) 機能の全てを一から記述しています。 単に自分自身でオブジェクト指向のコードを書く方法を探しているなら、 おそらく CPAN から L に記述されているオブジェクトシステムの 一つを使うことによってよりよく扱えるでしょう。 =begin original If you're looking to write your own object system, or you need to maintain code which implements objects from scratch then this document will help you understand exactly how Perl does object orientation. =end original 自分自身のオブジェクトシステムの書き方を探していたり、 一からオブジェクトを実装しているコードを保守する必要があるなら、 この文書はどうやって Perl がオブジェクト指向を行っているかを正確に 理解する助けになるでしょう。 =begin original There are a few basic principles which define object oriented Perl: =end original オブジェクト指向 Perl を定義するいくつかの基本的な原則があります: =over 4 =item 1. =begin original An object is simply a data structure that knows to which class it belongs. =end original オブジェクトは単に、どのクラスに属するかを知っているデータ構造です。 =item 2. =begin original A class is simply a package. A class provides methods that expect to operate on objects. =end original クラスは単にパッケージです。 クラスはオブジェクトを操作することを想定したメソッドを提供します。 =item 3. =begin original A method is simply a subroutine that expects a reference to an object (or a package name, for class methods) as the first argument. =end original メソッドは単に、最初の引数としてオブジェクト (またはクラスメソッドの場合は パッケージ名) を想定するサブルーチンです。 =back =begin original Let's look at each of these principles in depth. =end original それぞれの原則を深く見てみましょう。 =head2 An Object is Simply a Data Structure X X X X (オブジェクトは単なるデータ構造) =begin original Unlike many other languages which support object orientation, Perl does not provide any special syntax for constructing an object. Objects are merely Perl data structures (hashes, arrays, scalars, filehandles, etc.) that have been explicitly associated with a particular class. =end original オブジェクト指向に対応しているその他の多くの言語と違って、 Perl はオブジェクトを構築するための特別な文法を提供していません。 オブジェクトは、特定のクラスと明示的に関連付けられている 単なる Perl データ構造(ハッシュ、配列、スカラ、ファイルハンドルなど)です。 =begin original That explicit association is created by the built-in C function, which is typically used within the I subroutine of the class. =end original 明示的な関連付けは組み込みの C 関数によって作られます; これは典型的にはクラスの I<コンストラクタ> サブルーチンの中で使われます。 =begin original Here is a simple constructor: =end original 以下は単純なコンストラクタです: package File; sub new { my $class = shift; return bless {}, $class; } =begin original The name C isn't special. We could name our constructor something else: =end original C という名前は特別ではありません。 コンストラクタに他の名前を付けることも出来ます: package File; sub load { my $class = shift; return bless {}, $class; } =begin original The modern convention for OO modules is to always use C as the name for the constructor, but there is no requirement to do so. Any subroutine that blesses a data structure into a class is a valid constructor in Perl. =end original OO モジュールのモダンな慣習は、コンストラクタの名前として 常に C を使うというものですが、そうする必要性はありません。 データ構造をクラスに bless するどんなサブルーチンも Perl での 正当なコンストラクタです。 =begin original In the previous examples, the C<{}> code creates a reference to an empty anonymous hash. The C function then takes that reference and associates the hash with the class in C<$class>. In the simplest case, the C<$class> variable will end up containing the string "File". =end original 前述の例で、C<{}> というコードは、空の無名ハッシュへのリファレンスを 作ります。 それから C 変数はこのリファレンスを取り、ハッシュを C<$class> のクラスと関連付けます。 最も単純な場合では、C<$class> 変数は "File" という文字列を含んでいます。 =begin original We can also use a variable to store a reference to the data structure that is being blessed as our object: =end original また、オブジェクトとして bless するデータ構造へのリファレンスを補完する 変数を使うことも出来ます: sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } =begin original Once we've blessed the hash referred to by C<$self> we can start calling methods on it. This is useful if you want to put object initialization in its own separate method: =end original C<$self> で参照されているハッシュを bless すれば、 それに含まれるメソッドを呼び出し始められます。 オブジェクトの初期化を独自の分離されたメソッドで行いたい場合に これは有用です: sub new { my $class = shift; my $self = {}; bless $self, $class; $self->_initialize(); return $self; } =begin original Since the object is also a hash, you can treat it as one, using it to store data associated with the object. Typically, code inside the class can treat the hash as an accessible data structure, while code outside the class should always treat the object as opaque. This is called B. Encapsulation means that the user of an object does not have to know how it is implemented. The user simply calls documented methods on the object. =end original オブジェクトはハッシュでもあるので、これをハッシュとして扱うことが出来、 オブジェクトに関連付けられているデータを保管するのに使えます。 典型的には、クラス内のコードはハッシュをアクセス可能なデータ構造として 扱い、クラスの外側のコードは常にオブジェクトを不透明なものとして 扱うべきです。 これは B<カプセル化> と呼ばれます。 カプセル化とは、オブジェクトのユーザーはそれがどのように実装されているかを 知る必要がないということです。 ユーザーは単にオブジェクトの文書化されたメソッドを呼び出します。 =begin original Note, however, that (unlike most other OO languages) Perl does not ensure or enforce encapsulation in any way. If you want objects to actually I opaque you need to arrange for that yourself. This can be done in a variety of ways, including using L<"Inside-Out objects"> or modules from CPAN. =end original しかし、(その他の OO 言語のほとんどと違って) Perl はなんらかの方法で カプセル化を保証したり強制したりしません。 もしあなたがオブジェクトを本当に不透明に I<する> ことを望むなら、 あなた自身でそうなるように準備する必要があります。 これをするには、L<"Inside-Out objects"> や CPAN のモジュールを使うことを 含めて様々な方法があります。 =head3 Objects Are Blessed; Variables Are Not (オブジェクトは bless されている; 変数はされていない) =begin original When we bless something, we are not blessing the variable which contains a reference to that thing, nor are we blessing the reference that the variable stores; we are blessing the thing that the variable refers to (sometimes known as the I). This is best demonstrated with this code: =end original 私たちが何かを bless するとき、 私たちはそのものへのリファレンスを含んでいる変数を bless しているのではなく、 変数に保管されているリファレンスを bless しているのでもありません。 私たちは変数が参照している何か(時々 I<参照先> (referent) として知られます) を bless しています。 これはこのコードで最も良く表されています: use Scalar::Util 'blessed'; my $foo = {}; my $bar = $foo; bless $foo, 'Class'; print blessed( $bar ); # prints "Class" $bar = "some other value"; print blessed( $bar ); # prints undef =begin original When we call C on a variable, we are actually blessing the underlying data structure that the variable refers to. We are not blessing the reference itself, nor the variable that contains that reference. That's why the second call to C returns false. At that point C<$bar> is no longer storing a reference to an object. =end original 変数に対して C を呼び出すと、実際には変数が参照している 基となるデータ構造を bless しています。 リファレンス自身や、リファレンスを保管している変数を bless しているのでは ありません。 これが、2 番目の C が偽を返す理由です。 この時点では C<$bar> はもはやオブジェクトへのリファレンスを 保管していません。 =begin original You will sometimes see older books or documentation mention "blessing a reference" or describe an object as a "blessed reference", but this is incorrect. It isn't the reference that is blessed as an object; it's the thing the reference refers to (i.e. the referent). =end original 時々古い本や文書で「リファレンスを bless する」という記述や、 オブジェクトのことを「bless されたリファレンス」と説明しているのを 見るかも知れませんが、これは不正確です。 bless されたリファレンスがオブジェクトなのではありません; リファレンスが参照しているもの (つまり参照先) です。 =head2 A Class is Simply a Package X X X<@ISA> X (クラスは単なるパッケージ) =begin original Perl does not provide any special syntax for class definitions. A package is simply a namespace containing variables and subroutines. The only difference is that in a class, the subroutines may expect a reference to an object or the name of a class as the first argument. This is purely a matter of convention, so a class may contain both methods and subroutines which I operate on an object or class. =end original Perl はクラス定義のための特別な文法を提供しません。 パッケージは変数とサブルーチンを含む単なる名前空間です。 クラスとの唯一の違いは、サブルーチンはその最初の引数に オブジェクトへのリファレンスかクラス名を想定すると言うことです。 これは純粋に規約の問題なので、一つのクラスにメソッドと、オブジェクトや クラスを操作 I<しない> サブルーチンの両方を含むことも出来ます。 =begin original Each package contains a special array called C<@ISA>. The C<@ISA> array contains a list of that class's parent classes, if any. This array is examined when Perl does method resolution, which we will cover later. =end original 各パッケージは C<@ISA> と呼ばれる特別な配列を持ちます。 C<@ISA> 配列は (もしあれば) そのクラスの親クラスの一覧からなります。 この配列は、後述する、Perl がメソッド解決をするときにチェックされます。 =begin original It is possible to manually set C<@ISA>, and you may see this in older Perl code. Much older code also uses the L pragma. For new code, we recommend that you use the L pragma to declare your parents. This pragma will take care of setting C<@ISA>. It will also load the parent classes and make sure that the package doesn't inherit from itself. =end original 手動で C<@ISA> は可能で、古い Perl コードではそれを見るかも知れません。 さらに古いコードでは L プラグマも使います。 新しいコードでは、親を宣言するために we recommend that you use the L プラグマを使うことを勧めます。 このプラグマは C<@ISA> の設定の世話をします。 これはまた、親クラスを読み込んで、パッケージがそれ自身から 継承されていないことを確認します。 =begin original However the parent classes are set, the package's C<@ISA> variable will contain a list of those parents. This is simply a list of scalars, each of which is a string that corresponds to a package name. =end original しかし、親クラスが設定されると、そのパッケージの C<@ISA> 変数は それらの親のリストになります。 これは単純にスカラのリストで、それぞれはパッケージ名に対応する 文字列です。 =begin original All classes inherit from the L class implicitly. The L class is implemented by the Perl core, and provides several default methods, such as C, C, and C. The C class will I appear in a package's C<@ISA> variable. =end original 全てのクラスは暗黙に L クラスから継承されます。 L クラスは Perl コアによって実装されていて、 C, C, and C のようないくつかのデフォルトメソッドを 提供します。 C クラスは I<決して> パッケージの C<@ISA> 変数に表れません。 =begin original Perl I provides method inheritance as a built-in feature. Attribute inheritance is left up the class to implement. See the L section for details. =end original Perl は組み込み機能としてメソッド継承 I<のみ> を提供します。 属性継承は実装されるクラスに残されています。 詳しくは L 節を参照してください。 =head2 A Method is Simply a Subroutine X (メソッドは単なるサブルーチン) =begin original Perl does not provide any special syntax for defining a method. A method is simply a regular subroutine, and is declared with C. What makes a method special is that it expects to receive either an object or a class name as its first argument. =end original Perl はメソッドを定義するための特別な文法を提供しません。 メソッドは単に通常のサブルーチンで、C によって宣言されます。 メソッドを特別にしているのは、それが最初の引数として オブジェクトかクラス名を受け取ることを想定していると言うことです。 =begin original Perl I provide special syntax for method invocation, the C<< -> >> operator. We will cover this in more detail later. =end original Perl には C<< -> >> 演算子というメソッド起動のための特別な文法が I<あります>。 後にこれに関する詳細を取り上げます。 =begin original Most methods you write will expect to operate on objects: =end original あなたの書くほとんどのメソッドはオブジェクトを操作することを想定します: sub save { my $self = shift; open my $fh, '>', $self->path() or die $!; print {$fh} $self->data() or die $!; close $fh or die $!; } =head2 Method Invocation X X X X<< -> >> (メソッドの起動) =begin original Calling a method on an object is written as C<< $object->method >>. =end original オブジェクトのメソッドの呼び出しは C<< $object->method >> のように書けます。 =begin original The left hand side of the method invocation (or arrow) operator is the object (or class name), and the right hand side is the method name. =end original メソッド起動 (つまり矢印) 演算子の左側はオブジェクト(またはメソッド名)で、 右側はメソッド名です。 my $pod = File->new( 'perlobj.pod', $data ); $pod->save(); =begin original The C<< -> >> syntax is also used when dereferencing a reference. It looks like the same operator, but these are two different operations. =end original C<< -> >> 文法は、リファレンスをデリファレンスするためにも使われます。 これは同じ演算子のように見えますが、これらは二つの異なった処理です。 =begin original When you call a method, the thing on the left side of the arrow is passed as the first argument to the method. That means when we call C<< Critter->new() >>, the C method receives the string C<"Critter"> as its first argument. When we call C<< $fred->speak() >>, the C<$fred> variable is passed as the first argument to C. =end original メソッドを呼び出すとき、矢印の左側のものがメソッドの最初の引数として 渡されます。 つまり、C<< Critter->new() >> を呼び出すと、 C メソッドは最初の引数として文字列 C<"Critter"> を受け取ります。 C<< $fred->speak() >> を呼び出すと、 C<$fred> 変数が C の最初の引数として渡されます。 =begin original Just as with any Perl subroutine, all of the arguments passed in C<@_> are aliases to the original argument. This includes the object itself. If you assign directly to C<$_[0]> you will change the contents of the variable that holds the reference to the object. We recommend that you don't do this unless you know exactly what you're doing. =end original 他の Perl のサブルーチンと同様、C<@_> で渡される全ての引数は 元の引数への別名です。 これにはオブジェクト自身も含まれます。 C<$_[0]> に直接代入すると、オブジェクトへのリファレンスを 保持している変数の内容を変更します。 あなたが何をしているのかを正確に分かっていない限り、 これをしないことを勧めます。 =begin original Perl knows what package the method is in by looking at the left side of the arrow. If the left hand side is a package name, it looks for the method in that package. If the left hand side is an object, then Perl looks for the method in the package that the object has been blessed into. =end original Perl は、矢印の左側を見ることで、メソッドがどのパッケージにあるかを知ります。 左側がパッケージ名なら、そのパッケージのメソッドを探します。 左側がオブジェクトなら、Perl はオブジェクトに bless されている パッケージのメソッドを探します。 =begin original If the left hand side is neither a package name nor an object, then the method call will cause an error, but see the section on L for more nuances. =end original 左側がパッケージ名でもオブジェクトでもない場合、メソッド呼び出しは エラーになりますが、さらなるニュアンスについては L の説を参照してください。 =head2 Inheritance X (継承) =begin original We already talked about the special C<@ISA> array and the L pragma. =end original 特別な C<@ISA> 配列と L プラグマについては既に話しました。 =begin original When a class inherits from another class, any methods defined in the parent class are available to the child class. If you attempt to call a method on an object that isn't defined in its own class, Perl will also look for that method in any parent classes it may have. =end original あるクラスが他のクラスを継承すると、親クラスで定義されているどのメソッドも 子クラスで利用可能です。 あるオブジェクトで自分自身のクラスで定義されていないメソッドを 呼び出そうとすると、Perl は親クラスにあるメソッドも探します。 package File::MP3; use parent 'File'; # sets @File::MP3::ISA = ('File'); my $mp3 = File::MP3->new( 'Andvari.mp3', $data ); $mp3->save(); =begin original Since we didn't define a C method in the C class, Perl will look at the C class's parent classes to find the C method. If Perl cannot find a C method anywhere in the inheritance hierarchy, it will die. =end original C クラスに C メソッドを定義していないので、 Perl は C メソッドを見つけるために C クラスの 親クラスを見ます。 Perl が継承階層のどこにも C メソッドを見つけられないと、 die します。 =begin original In this case, it finds a C method in the C class. Note that the object passed to C in this case is still a C object, even though the method is found in the C class. =end original この場合、C クラスの C メソッドを見つけます。 この場合、メソッドは C クラスで見つかったとしても、 C に渡されるオブジェクトはやはり C であることに 注意してください。 =begin original We can override a parent's method in a child class. When we do so, we can still call the parent class's method with the C pseudo-class. =end original 子クラスのメソッドで親クラスのメソッドをオーバーライドできます。 そうしたとき、C 疑似クラスで親クラスのメソッドを呼び出すことも 出来ます。 sub save { my $self = shift; say 'Prepare to rock'; $self->SUPER::save(); } =begin original The C modifier can I be used for method calls. You can't use it for regular subroutine calls or class methods: =end original C 修飾子はメソッド呼び出しで I<のみ> 使えます。 通常のサブルーチン呼び出しやクラスメソッドでは使えません: SUPER::save($thing); # FAIL: looks for save() sub in package SUPER SUPER->save($thing); # FAIL: looks for save() method in class # SUPER $thing->SUPER::save(); # Okay: looks for save() method in parent # classes =head3 How SUPER is Resolved X (SUPER はどのように解決されるか) =begin original The C pseudo-class is resolved from the package where the call is made. It is I resolved based on the object's class. This is important, because it lets methods at different levels within a deep inheritance hierarchy each correctly call their respective parent methods. =end original C 疑似クラスは、呼び出しが行われたパッケージから解決されます。 これはオブジェクトのクラスを元にして解決 I<されません> 。 これは重要です; なぜならこれにより 深い継承階層でそれぞれ異なったレベルにあるメソッドが それぞれの親メソッドを正しく呼び出せるようになるからです。 package A; sub new { return bless {}, shift; } sub speak { my $self = shift; say 'A'; } package B; use parent -norequire, 'A'; sub speak { my $self = shift; $self->SUPER::speak(); say 'B'; } package C; use parent -norequire, 'B'; sub speak { my $self = shift; $self->SUPER::speak(); say 'C'; } my $c = C->new(); $c->speak(); =begin original In this example, we will get the following output: =end original この例では、次のような出力になります: A B C =begin original This demonstrates how C is resolved. Even though the object is blessed into the C class, the C method in the C class can still call C and expect it to correctly look in the parent class of C (i.e the class the method call is in), not in the parent class of C (i.e. the class the object belongs to). =end original これはどのように C が解決されるかを図示します。 たとえオブジェクトが C クラスに bless されていても、 C クラスの C メソッドはまだ C を呼び出して、正しく C (つまりメソッド呼び出しされた クラス)の親クラスを見ることを想定します; C (つまりオブジェクトが属するクラス) の親クラスではありません。 =begin original There are rare cases where this package-based resolution can be a problem. If you copy a subroutine from one package to another, C resolution will be done based on the original package. =end original このパッケージを基にした解決が問題になる稀な場合があります。 サブルーチンをあるパッケージから他にコピーすると、 C の解決は元のパッケージを基にして行われます。 =head3 Multiple Inheritance X (多重継承) =begin original Multiple inheritance often indicates a design problem, but Perl always gives you enough rope to hang yourself with if you ask for it. =end original 多重継承はしばしば設計上の問題を表しますが、しかしあなたが求めるなら、 Perl は常にあなた自身がぶら下がるのに十分なロープを与えます。 =begin original To declare multiple parents, you simply need to pass multiple class names to C: =end original 多重継承を宣言するには、 単に複数のクラス名を C に渡す必要があります: package MultiChild; use parent 'Parent1', 'Parent2'; =head3 Method Resolution Order X X (メソッド解決順序) =begin original Method resolution order only matters in the case of multiple inheritance. In the case of single inheritance, Perl simply looks up the inheritance chain to find a method: =end original メソッド解決順序は多重継承の場合にのみ問題になります。 単一継承の場合は、Perl はメソッドを見つけるために単純に継承チェーンを 探します: Grandparent | Parent | Child =begin original If we call a method on a C object and that method is not defined in the C class, Perl will look for that method in the C class and then, if necessary, in the C class. =end original C オブジェクトのメソッドを呼び出して、そのメソッドが C クラスに定義されていない場合、 Perl はC クラスのメソッドを探し、 それからもし必要なら C クラスを探します。 =begin original If Perl cannot find the method in any of these classes, it will die with an error message. =end original Perl がこれらのクラスのどこからもこのメソッドを見つけられない場合、 エラーメッセージと共に die します。 =begin original When a class has multiple parents, the method lookup order becomes more complicated. =end original クラスが複数の親を持つとき、メソッド検索順序はより複雑になります。 =begin original By default, Perl does a depth-first left-to-right search for a method. That means it starts with the first parent in the C<@ISA> array, and then searches all of its parents, grandparents, etc. If it fails to find the method, it then goes to the next parent in the original class's C<@ISA> array and searches from there. =end original デフォルトでは、Perl はメソッドに対して深さ優先左から右探索を行います。 つまり、C<@ISA> 配列の最初の親から始め、それからその全ての親、祖父母、 というように探索します。 メソッドを見つけることに失敗すると、元のクラスの C<@ISA> 配列の 次の親に行き、そこから探索します。 SharedGreatGrandParent / \ PaternalGrandparent MaternalGrandparent \ / Father Mother \ / Child =begin original So given the diagram above, Perl will search C, C, C, C, C, and finally C. This may be a problem because now we're looking in C I we've checked all its derived classes (i.e. before we tried C and C). =end original 従って、前述した図の場合、Perl は C, C, C, C, C そして最後に C を探索します。 これは C クラスを、その全ての派生クラスを チェックする (つまり C と C を試す) I<前に> 見るので、問題があるかも知れません。 =begin original It is possible to ask for a different method resolution order with the L pragma. =end original L プラグマで異なったメソッド解決順序を使うようにすることができます。 package Child; use mro 'c3'; use parent 'Father', 'Mother'; =begin original This pragma lets you switch to the "C3" resolution order. In simple terms, "C3" order ensures that shared parent classes are never searched before child classes, so Perl will now search: C, C, C, C C, and finally C. Note however that this is not "breadth-first" searching: All the C ancestors (except the common ancestor) are searched before any of the C ancestors are considered. =end original このプラグマは "C3" 解決順序に切り替えます。 簡単に言えば、"C3" 順序は 共有親クラスが子クラスより先に探索されないことを保証するので、 Perl は次の順で探索するようになります: C, C, C, C C そして最後に C。 しかし、これは「幅優先」探索ではないことに注意してください: (共通の祖先を除く) 全ての C の祖先は、 C の祖先より前に探索されます。 =begin original The C3 order also lets you call methods in sibling classes with the C pseudo-class. See the L documentation for more details on this feature. =end original C3 順序はまた、C 疑似クラスで兄弟クラスのメソッドを 呼び出せるようにします。 この機能に関するさらなる詳細については L 文書を参照してください。 =head3 Method Resolution Caching (メソッド解決キャッシュ) =begin original When Perl searches for a method, it caches the lookup so that future calls to the method do not need to search for it again. Changing a class's parent class or adding subroutines to a class will invalidate the cache for that class. =end original Perl がメソッドを探すとき、結果をキャッシュするので、 そのメソッドを将来呼び出しても再び探す必要はありません。 クラスの親クラスが変更されたり、クラスにサブルーチンが追加されると、 そのクラスのキャッシュは無効化されます。 =begin original The L pragma provides some functions for manipulating the method cache directly. =end original L プラグマはメソッドキャッシュを直接操作するための いくつかの関数を提供します。 =head2 Writing Constructors X (コンストラクタを書く) =begin original As we mentioned earlier, Perl provides no special constructor syntax. This means that a class must implement its own constructor. A constructor is simply a class method that returns a reference to a new object. =end original 前述したように、Perl はコンストラクタのための特別な文法を提供しません。 つまり、クラスは自身のコンストラクタを実装しなければなりません。 コンストラクタは新しいオブジェクトへのリファレンスを返す単なる クラスメソッドです。 =begin original The constructor can also accept additional parameters that define the object. Let's write a real constructor for the C class we used earlier: =end original コンストラクタはまた、オブジェクトを定義するための追加の引数を受け取れます。 以前に使った C クラスの実際のコンストラクタを書いてみましょう: package File; sub new { my $class = shift; my ( $path, $data ) = @_; my $self = bless { path => $path, data => $data, }, $class; return $self; } =begin original As you can see, we've stored the path and file data in the object itself. Remember, under the hood, this object is still just a hash. Later, we'll write accessors to manipulate this data. =end original ここで見られるように、パスとファイルデータをオブジェクト自身に 保管しています。 水面下では、このオブジェクトはまだ単なるハッシュであることを 忘れないでください。 後で、このデータを操作するためのアクセサを書きます。 =begin original For our File::MP3 class, we can check to make sure that the path we're given ends with ".mp3": =end original この File::MP3 クラスのために、与えられたパスが ".mp3" で終わっているかを チェックできます: package File::MP3; sub new { my $class = shift; my ( $path, $data ) = @_; die "You cannot create a File::MP3 without an mp3 extension\n" unless $path =~ /\.mp3\z/; return $class->SUPER::new(@_); } =begin original This constructor lets its parent class do the actual object construction. =end original このコンストラクタは親クラスに実際のオブジェクト構築を行わせます。 =head2 Attributes X (属性) =begin original An attribute is a piece of data belonging to a particular object. Unlike most object-oriented languages, Perl provides no special syntax or support for declaring and manipulating attributes. =end original 属性は特定のオブジェクトに所属するデータ片です。 ほとんどのオブジェクト指向言語と異なり、Perl は属性の宣言や操作に 対応する特別な文法を提供しません。 =begin original Attributes are often stored in the object itself. For example, if the object is an anonymous hash, we can store the attribute values in the hash using the attribute name as the key. =end original 属性はしばしばオブジェクト自身に保管されます。 例えば、オブジェクトが無名ハッシュなら、属性名をキーとして使って そのハッシュに属性値を保管できます。 =begin original While it's possible to refer directly to these hash keys outside of the class, it's considered a best practice to wrap all access to the attribute with accessor methods. =end original これらのハッシュキーをクラスの外側から直接参照することは可能ですが、 全ての属性へのアクセスをアクセサメソッドで包むのがベストプラクティスと 考えられています。 =begin original This has several advantages. Accessors make it easier to change the implementation of an object later while still preserving the original API. =end original これにはいくつかの利点があります。 アクセサは、後に元の API を保存したままオブジェクトの実装を 変更するのをより簡単にします。 =begin original An accessor lets you add additional code around attribute access. For example, you could apply a default to an attribute that wasn't set in the constructor, or you could validate that a new value for the attribute is acceptable. =end original アクセサは属性アクセスに関する追加のコードを追加できるようにします。 例えば、コンストラクタで設定されない属性のデフォルトを適用したり、 属性の新しい値が受け入れられるかの検証をしたり出来ます。 =begin original Finally, using accessors makes inheritance much simpler. Subclasses can use the accessors rather than having to know how a parent class is implemented internally. =end original 最後に、アクセサを使うと継承が遙かに簡単になります。 サブクラスはアクセサを使うことで、親クラスが内部でどのように 実装されているかを知る必要がなくなります。 =head3 Writing Accessors X (アクセサを書く) =begin original As with constructors, Perl provides no special accessor declaration syntax, so classes must provide explicitly written accessor methods. There are two common types of accessors, read-only and read-write. =end original コンストラクタと同様、Perl は特別なアクセサ宣言文法を持たないので、 クラスは明示的に書かれたアクセサメソッドを提供しなければなりません。 アクセサには 2 種類あります; 読み込み専用と読み書き用です。 =begin original A simple read-only accessor simply gets the value of a single attribute: =end original 単純な読み込み専用アクセサは単純に単一の属性の値を取得します: sub path { my $self = shift; return $self->{path}; } =begin original A read-write accessor will allow the caller to set the value as well as get it: =end original 読み書きアクセサは、呼び出し側が取得と共に値の設定もできるようにします: sub path { my $self = shift; if (@_) { $self->{path} = shift; } return $self->{path}; } =head2 An Aside About Smarter and Safer Code (より賢く安全なコードのための余談) =begin original Our constructor and accessors are not very smart. They don't check that a C<$path> is defined, nor do they check that a C<$path> is a valid filesystem path. =end original このコンストラクタとアクセサはあまり賢くありません。 C<$path> が定義されているかをチェックしませんし、 C<$path> が有効なファイルシステムパスかをチェックしません。 =begin original Doing these checks by hand can quickly become tedious. Writing a bunch of accessors by hand is also incredibly tedious. There are a lot of modules on CPAN that can help you write safer and more concise code, including the modules we recommend in L. =end original これらのチェックを手で書くのはすぐに退屈になります。 たくさんのアクセサを手で書くのもとても退屈です。 より安全でより簡潔なコードを書くことを助けるための、 L で推奨されているモジュールを含む多くのモジュールが CPAN にあります。 =head2 Method Call Variations X (メソッド呼び出しのバリエーション) =begin original Perl supports several other ways to call methods besides the C<< $object->method() >> usage we've seen so far. =end original Perl には C<< $object->method() >> という使用法以外にもメソッドを呼び出す 方法がいくつかあるのでそれを見ていきます。 =head3 Method Names as Strings (文字列としてのメソッド名) =begin original Perl lets you use a scalar variable containing a string as a method name: =end original Perl は文字列を含むスカラ変数をメソッド名として使うことを許しています: my $file = File->new( $path, $data ); my $method = 'save'; $file->$method(); =begin original This works exactly like calling C<< $file->save() >>. This can be very useful for writing dynamic code. For example, it allows you to pass a method name to be called as a parameter to another method. =end original これは正確に C<< $file->save() >> 呼び出しと同様です。 これは動的コードを書くのにとても有用です。 例えば、他のメソッドの引数として呼び出されるメソッド名を渡せるようになります。 =head3 Class Names as Strings (文字列としてのクラス名) =begin original Perl also lets you use a scalar containing a string as a class name: =end original Perl は文字列を含むスカラをクラス名として使うことを許しています: my $class = 'File'; my $file = $class->new( $path, $data ); =begin original Again, this allows for very dynamic code. =end original 再び、これによりとても動的なコードが書けます。 =head3 Subroutine References as Methods (メソッドとしてのサブルーチンリファレンス) =begin original You can also use a subroutine reference as a method: =end original サブルーチンリファレンスをメソッドとして使うことも出来ます: my $sub = sub { my $self = shift; $self->save(); }; $file->$sub(); =begin original This is exactly equivalent to writing C<< $sub->($file) >>. You may see this idiom in the wild combined with a call to C: =end original これは C<< $sub->($file) >> と書くのと正確に等価です。 世の中ではこの慣用句を C の呼び出しと結びつけられているのを 見ることがあるでしょう: if ( my $meth = $object->can('foo') ) { $object->$meth(); } =head3 Deferencing Method Call (メソッド呼び出しのデリファレンス) =begin original Perl also lets you use a dereferenced scalar reference in a method call. That's a mouthful, so let's look at some code: =end original Perl はまた、メソッド呼び出しの中でデリファレンスされたスカラリファレンスを 使うことを許しています。 これは分かりにくいので、コードを見てください: $file->${ \'save' }; $file->${ returns_scalar_ref() }; $file->${ \( returns_scalar() ) }; $file->${ returns_ref_to_sub_ref() }; =begin original This works if the dereference produces a string I a subroutine reference. =end original これは、デリファレンスが文字列 I<または> サブルーチンリファレンスを 生成するときに動作します。 =head3 Method Calls on Filehandles (ファイルハンドルでのメソッド呼び出し) =begin original Under the hood, Perl filehandles are instances of the C or C class. Once you have an open filehandle, you can call methods on it. Additionally, you can call methods on the C, C, and C filehandles. =end original 水面下では、Perl のファイルハンドルは C または C クラスのインスタンスです。 一度ファイルハンドルを開くと、そのメソッドを呼び出せます。 さらに、C, C, C ファイルハンドルのメソッドを 呼び出せます。 open my $fh, '>', 'path/to/file'; $fh->autoflush(); $fh->print('content'); STDOUT->autoflush(); =head2 Invoking Class Methods X (クラスメソッドの起動) =begin original Because Perl allows you to use barewords for package names and subroutine names, it sometimes interprets a bareword's meaning incorrectly. For example, the construct C<< Class->new() >> can be interpreted as either C<< 'Class'->new() >> or C<< Class()->new() >>. In English, that second interpretation reads as "call a subroutine named Class(), then call new() as a method on the return value of Class()". If there is a subroutine named C in the current namespace, Perl will always interpret C<< Class->new() >> as the second alternative: a call to C on the object returned by a call to C =end original Perl はパッケージ名とサブルーチン名に裸の単語を使うことを許しているので、 時々裸の単語の意味を誤って解釈します。 例えば、C<< Class->new() >> という構文は、 C<< 'Class'->new() >> または C<< Class()->new() >> のどちらでも解釈できます。 英語では、2 番目の解釈は「Class() という名前のサブルーチンを呼び出し、 それから Class() の返り値のメソッドとして new() を呼び出す」と読めます。 現在の名前空間に C という名前のサブルーチンがある場合、 Perl は常に C<< Class->new() >> を 2 番目の選択肢のように解釈します: C から返されたオブジェクトの C を呼び出します。 =begin original You can force Perl to use the first interpretation (i.e. as a method call on the class named "Class") in two ways. First, you can append a C<::> to the class name: =end original 二つの方法で最初の解釈 (つまり "Class" というクラスのメソッド呼び出し) を Perl に強制できます。 まず、C<::> をクラス名に追加できます: Class::->new() =begin original Perl will always interpret this as a method call. =end original Perl は常にこれをメソッド呼び出しとして解釈します。 =begin original Alternatively, you can quote the class name: =end original あるいは、クラス名をクォートできます: 'Class'->new() =begin original Of course, if the class name is in a scalar Perl will do the right thing as well: =end original もちろん、クラス名がスカラであれば Perl は同様に正しいことを行います: my $class = 'Class'; $class->new(); =head3 Indirect Object Syntax X (間接オブジェクト文法) =begin original B =end original B<ファイルハンドルの場合を除いて、この文法の使用は非推奨です; Perl インタプリタを混乱させることがあるからです。 さらなる詳細については以降を参照してください。> =begin original Perl supports another method invocation syntax called "indirect object" notation. This syntax is called "indirect" because the method comes before the object it is being invoked on. =end original Perl は、「間接オブジェクト」記法と呼ばれるもう一つのメソッド起動文法に 対応しています。 この文法は、起動されるオブジェクトの前にメソッド名が来るので 「間接」と呼ばれます。 =begin original This syntax can be used with any class or object method: =end original この文法は任意のクラスおよびオブジェクトメソッドで使えます: my $file = new File $path, $data; save $file; =begin original We recommend that you avoid this syntax, for several reasons. =end original いくつかの理由により、この文法は避けることを勧めます。 =begin original First, it can be confusing to read. In the above example, it's not clear if C is a method provided by the C class or simply a subroutine that expects a file object as its first argument. =end original まず、これは読むのに混乱することがあります。 前述の例では、C が C によって提供されるメソッドなのか 最初の引数としてファイルオブジェクトを想定する単なるサブルーチンなのかが はっきりしません。 =begin original When used with class methods, the problem is even worse. Because Perl allows subroutine names to be written as barewords, Perl has to guess whether the bareword after the method is a class name or subroutine name. In other words, Perl can resolve the syntax as either C<< File->new( $path, $data ) >> B C<< new( File( $path, $data ) ) >>. =end original クラスメソッドで使うとき、問題はさらに悪くなります。 Perl はサブルーチン名を裸の単語として書くことを許しているので、 メソッドの後の裸の単語がクラス名なのかサブルーチン名なのかを Perl が推測する必要があります。 言い換えると、Perl はこの文法を C<< File->new( $path, $data ) >> B<あるいは> C<< new( File( $path, $data ) ) >> と解釈できます。 =begin original To parse this code, Perl uses a heuristic based on what package names it has seen, what subroutines exist in the current package, what barewords it has previously seen, and other input. Needless to say, heuristics can produce very surprising results! =end original このコードをパースするために、 Perl はどんなパッケージ名が見られるか、どんなサブルーチンが現在の パッケージに存在するか、どんな裸の単語が以前に見られたか、 およびその他の入力を元にした経験則を使います。 言うまでもなく、経験則はとても驚く結果を招くことがあります! =begin original Older documentation (and some CPAN modules) encouraged this syntax, particularly for constructors, so you may still find it in the wild. However, we encourage you to avoid using it in new code. =end original より古い文書 (およびいくつかの CPAN モジュール) では、 特にコンストラクタについて、この文法を推奨していたので、 まだ世の中でこれを見ることがあるかもしれません。 しかし、新しいコードにこれを使うことは避けることを推奨します。 =begin original You can force Perl to interpret the bareword as a class name by appending "::" to it, like we saw earlier: =end original 以前に見たように、クラス名に "::" を付けることで、Perl が裸の単語として 解釈することを強制できます: my $file = new File:: $path, $data; =head2 C, C, and C (C, C, C) =begin original As we saw earlier, an object is simply a data structure that has been blessed into a class via the C function. The C function can take either one or two arguments: =end original 既に見たように、オブジェクトは C 関数でクラスに bless された 単なるデータ構造です。 C 関数は一つまたは二つの引数を取ります: my $object = bless {}, $class; my $object = bless {}; =begin original In the first form, the anonymous hash is being blessed into the class in C<$class>. In the second form, the anonymous hash is blessed into the current package. =end original 1 番目の形式では、無名ハッシュは C<$class> のクラスに bless されます。 2 番目の形式では、無名ハッシュは現在のパッケージに bless されます。 =begin original The second form is strongly discouraged, because it breaks the ability of a subclass to reuse the parent's constructor, but you may still run across it in existing code. =end original 2 番目の形式は強く非推奨です; なぜならこれは親のコンストラクタを 再利用するサブクラスの能力を壊すからです; しかし既に存在しているコードではまだこれを見ることがあるでしょう。 =begin original If you want to know whether a particular scalar refers to an object, you can use the C function exported by L, which is shipped with the Perl core. =end original あるスカラがオブジェクトを参照しているかどうかを知りたい場合、 Perl コアと同梱されている L からエクスポートされている C 関数が使えます。 use Scalar::Util 'blessed'; if ( defined blessed($thing) ) { ... } =begin original If C<$thing> refers to an object, then this function returns the name of the package the object has been blessed into. If C<$thing> doesn't contain a reference to a blessed object, the C function returns C. =end original C<$thing> がオブジェクトを参照しているなら、この関数はオブジェクトが bless されているパッケージ名を返します。 C<$thing> が bless されたオブジェクトへのリファレンスを含んでいないなら、 C 関数は C を返します。 =begin original Note that C will also return false if C<$thing> has been blessed into a class named "0". This is a possible, but quite pathological. Don't create a class named "0" unless you know what you're doing. =end original C<$thing> が "0" という名前のクラスに bless されている場合も C は偽を返すことに注意してください。 これは可能ですが、かなり極端です。 何をしているか分かっていない限り、"0" という名前のクラスを 作らないでください。 =begin original Similarly, Perl's built-in C function treats a reference to a blessed object specially. If you call C and C<$thing> holds a reference to an object, it will return the name of the class that the object has been blessed into. =end original 同様に、Perl の組み込みの C 関数は bless されたオブジェクトへの リファレンスを特別に扱います。 C を呼び出して、C<$thing> がオブジェクトへのリファレンスを 保持している場合、これはオブジェクトが bless されているクラス名を返します。 =begin original If you simply want to check that a variable contains an object reference, we recommend that you use C, since C returns true values for all references, not just objects. =end original 単純にある変数がオブジェクトリファレンスを含んでいるかをチェックしたい場合、 C を使うことを勧めます; C はオブジェクトだけでなく全てのリファレンスに関して真の値を 返すからです。 =head2 The UNIVERSAL Class X (UNIVERSAL クラス) =begin original All classes automatically inherit from the L class, which is built-in to the Perl core. This class provides a number of methods, all of which can be called on either a class or an object. You can also choose to override some of these methods in your class. If you do so, we recommend that you follow the built-in semantics described below. =end original 全てのクラスは、Perl コアに組み込まれている L クラスから 継承されます。 このクラスは、全てクラスまたはオブジェクトから呼ばれる いくつかのメソッドを提供します。 また、自身のクラスでこれらのメソッドのいくつかを オーバーライドすることを選ぶことも出来ます。 そうする場合は、後述する組み込みの意味論に従うことを勧めます。 =over 4 =item isa($class) X =begin original The C method returns I if the object is a member of the class in C<$class>, or a member of a subclass of C<$class>. =end original C メソッドは、オブジェクトが C<$class> のクラスか、C<$class> の サブクラスの場合に I<真> を返します。 =begin original If you override this method, it should never throw an exception. =end original このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。 =item DOES($role) X =begin original The C method returns I if its object claims to perform the role C<$role>. By default, this is equivalent to C. This method is provided for use by object system extensions that implement roles, like C and C. =end original C メソッドは、オブジェクトがロール C<$role> を実行すると主張している 場合に I<真> を返します。 デフォルトでは、これは C と等価です。 このメソッドは、C and C のように、ロールを実装している オブジェクトシステム拡張によって使われるために提供されています。 =begin original You can also override C directly in your own classes. If you override this method, it should never throw an exception. =end original また、自身のクラスで直接 C をオーバーライドすることも出来ます。 このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。 =item can($method) X =begin original The C method checks to see if the class or object it was called on has a method named C<$method>. This checks for the method in the class and all of its parents. If the method exists, then a reference to the subroutine is returned. If it does not then C is returned. =end original C メソッドは、呼び出されたクラスまたはオブジェクトが C<$method> という名前のメソッドを持っているかをチェックします。 これはそのクラスおよび全ての親のメソッドをチェックします。 メソッドが存在する場合、サブルーチンへのリファレンスを返します。 存在しなければ C が返されます。 =begin original If your class responds to method calls via C, you may want to overload C to return a subroutine reference for methods which your C method handles. =end original あなたのクラスが C 経由のメソッド呼び出しに対応する場合、 C メソッドが扱うメソッドについてサブルーチンリファレンスを 返すように C をオーバーロードした方が良いでしょう。 =begin original If you override this method, it should never throw an exception. =end original このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。 =item VERSION($need) X =begin original The C method returns the version number of the class (package). =end original C メソッドはクラス (パッケージ) のバージョン番号を返します。 =begin original If the C<$need> argument is given then it will check that the current version (as defined by the $VERSION variable in the package) is greater than or equal to C<$need>; it will die if this is not the case. This method is called automatically by the C form of C. =end original C<$need> 引数が指定された場合、現在のバージョン (パッケージの $VERSION 変数によって定義されているもの) が C<$need> 以上かどうかを チェックします; そうでない場合は die します。 このメソッドは C の C 形式によって自動的に呼び出されます。 use Package 1.2 qw(some imported subs); # implies: Package->VERSION(1.2); =begin original We recommend that you use this method to access another package's version, rather than looking directly at C<$Package::VERSION>. The package you are looking at could have overridden the C method. =end original 他のパッケージのバージョンにアクセスする場合は、直接 C<$Package::VERSION> を見るのではなくこのメソッドを使うことを勧めます。 見ようとしているパッケージは C メソッドを オーバーライドしているかも知れません。 =begin original We also recommend using this method to check whether a module has a sufficient version. The internal implementation uses the L module to make sure that different types of version numbers are compared correctly. =end original また、あるモジュールのバージョンが十分かどうかをチェックするのに このメソッドを使うことを勧めます。 内部実装は、異なった種類のバージョン番号が正しく比較されるように L モジュールを使います。 =back =head2 AUTOLOAD X =begin original If you call a method that doesn't exist in a class, Perl will throw an error. However, if that class or any of its parent classes defines an C method, that C method is called instead. =end original クラスに存在しないメソッドを呼び出すと、Perl は例外を投げます。 しかし、そのクラスまたは親クラスに C メソッドが定義されていると、代わりに C メソッドが 呼び出されます。 =begin original C is called as a regular method, and the caller will not know the difference. Whatever value your C method returns is returned to the caller. =end original C は通常のメソッドとして呼び出され、呼び出し元は 違いを知ることは出来ません。 C メソッドが返した値が呼び出し元に返されます。 =begin original The fully qualified method name that was called is available in the C<$AUTOLOAD> package global for your class. Since this is a global, if you want to refer to do it without a package name prefix under C, you need to declare it. =end original 呼び出された完全修飾メソッド名はあなたのクラスのパッケージグローバル変数 C<$AUTOLOAD> から利用可能です。 これはグローバルなので、 C の基でパッケージ名接頭辞なしでこれを参照したい場合は、 宣言する必要があります。 # XXX - this is a terrible way to implement accessors, but it makes # for a simple example. our $AUTOLOAD; sub AUTOLOAD { my $self = shift; # Remove qualifier from original method name... my $called = $AUTOLOAD =~ s/.*:://r; # Is there an attribute of that name? die "No such attribute: $called" unless exists $self->{$called}; # If so, return it... return $self->{$called}; } sub DESTROY { } # see below =begin original Without the C declaration, this code will not compile under the L pragma. =end original C 宣言なしだと、このコードは L プラグマの基ではコンパイル出来ません。 =begin original As the comment says, this is not a good way to implement accessors. It's slow and too clever by far. However, you may see this as a way to provide accessors in older Perl code. See L for recommendations on OO coding in Perl. =end original コメントにあるように、これはアクセサを実装するための良い方法ではありません。 これは遅く、はるかに賢すぎます。 しかし、古い Perl コードでアクセサを提供する方法としてこれを 見ることがあるかも知れません。 Perl での OO コーディングの推奨については L を参照してください。 =begin original If your class does have an C method, we strongly recommend that you override C in your class as well. Your overridden C method should return a subroutine reference for any method that your C responds to. =end original クラスに C メソッドがある場合、 C もオーバーライドすることを強く勧めます。 オーバーライドされた C メソッドは、C が対応する メソッドについてサブルーチンリファレンスを返すべきです。 =head2 Destructors X X (デストラクタ) =begin original When the last reference to an object goes away, the object is destroyed. If you only have one reference to an object stored in a lexical scalar, the object is destroyed when that scalar goes out of scope. If you store the object in a package global, that object may not go out of scope until the program exits. =end original オブジェクトへの最後のリファレンスがなくなると、オブジェクトは破壊されます。 オブジェクトへの一つのリファレンスをレキシカルなスカラに入れているだけの 場合、スカラがスコープ外に出るとオブジェクトは破壊されます。 オブジェクトをパッケージグローバルに保管すると、プログラムが終了するまで オブジェクトはなくならないかもしれません。 =begin original If you want to do something when the object is destroyed, you can define a C method in your class. This method will always be called by Perl at the appropriate time, unless the method is empty. =end original オブジェクトが破壊されるときに何かをしたい場合、 自分のクラスに C メソッドを定義できます。 このメソッドは、空でない限り、適切な時点で常に Perl によって呼び出されます。 =begin original This is called just like any other method, with the object as the first argument. It does not receive any additional arguments. However, the C<$_[0]> variable will be read-only in the destructor, so you cannot assign a value to it. =end original これは、他のメソッドと同様、オブジェクトを最初の引数として呼び出されます。 これは追加の引数は受け取りません。 しかし、C<$_[0]> 変数はデストラクタの中では読み込み専用なので、 これに値を代入することは出来ません。 =begin original If your C method throws an error, this error will be ignored. It will not be sent to C and it will not cause the program to die. However, if your destructor is running inside an C block, then the error will change the value of C<$@>. =end original C メソッドがエラーを投げた場合、このエラーは無視されます。 これは C に送られず、プログラムの die を引き起こしません。 しかし、デストラクタが C ブロックの中で実行されている場合、 エラーは C<$@> の値を変更します。 =begin original Because C methods can be called at any time, you should localize any global variables you might update in your C. In particular, if you use C you should localize C<$@>, and if you use C or backticks you should localize C<$?>. =end original C メソッドはあらゆる時点で呼び出される可能性があるので、 C の中で更新されるかも知れない全てのグローバル変数を ローカル化するべきです。 特に、C を使う場合は C<$@> をローカル化するべきで、 C や逆クォートを使う場合は C<$?> をローカル化するべきです。 =begin original If you define an C in your class, then Perl will call your C to handle the C method. You can prevent this by defining an empty C, like we did in the autoloading example. You can also check the value of C<$AUTOLOAD> and return without doing anything when called to handle C. =end original クラス内で C を定義している場合、 Perl は C メソッドを扱うために C を呼び出します。 オートロードの例で行ったように、空の C を定義することによって これを防げます。 また、C<$AUTOLOAD> の値をチェックして、C を扱うために 呼び出されたときには何もせずに返ることもできます。 =head3 Global Destruction (グローバルな破壊) =begin original The order in which objects are destroyed during the global destruction before the program exits is unpredictable. This means that any objects contained by your object may already have been destroyed. You should check that a contained object is defined before calling a method on it: =end original プログラムが終了する前のグローバルな破壊の間にオブジェクトが破壊される 順序は予測できません。 つまり、あなたのオブジェクトに含まれているオブジェクトは既に 破壊されているかも知れないということです。 含まれているオブジェクトを呼び出す前にそのメソッドが定義されているかどうかを チェックするべきです: sub DESTROY { my $self = shift; $self->{handle}->close() if $self->{handle}; } =begin original You can use the C<${^GLOBAL_PHASE}> variable to detect if you are currently in the global destruction phase: =end original 現在グローバル破壊フェーズ中なのかを検出するために、 C<${^GLOBAL_PHASE}> 変数が使えます: sub DESTROY { my $self = shift; return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; $self->{handle}->close(); } =begin original Note that this variable was added in Perl 5.14.0. If you want to detect the global destruction phase on older versions of Perl, you can use the C module on CPAN. =end original この変数は Perl 5.14.0 で追加されたことに注意してください。 より古いバージョンの Perl でグローバル破壊フェーズを検出したい場合は、 CPAN の C モジュールを使えます。 =begin original If your C method issues a warning during global destruction, the Perl interpreter will append the string " during global destruction" the warning. =end original C メソッドがグローバルな破壊中に警告を出した場合、 Perl インタプリタは警告に " during global destruction" という文字列を 追加します。 =begin original During global destruction, Perl will always garbage collect objects before unblessed references. See L for more information about global destruction. =end original グローバルな破壊の間、Perl は常にリファレンスの bless 解除の前に オブジェクトをガベージコレクションします。 グローバルな破壊に関するさらなる情報については L を参照してください。 =head2 Non-Hash Objects (非ハッシュオブジェクト) =begin original All the examples so far have shown objects based on a blessed hash. However, it's possible to bless any type of data structure or referent, including scalars, globs, and subroutines. You may see this sort of thing when looking at code in the wild. =end original 今までの全ての例ではオブジェクトは bless されたハッシュを基にしていました。 しかし、スカラ、グロブ、サブルーチンを含むあらゆる種類のデータ構造や 参照先を bless することが出来ます。 世の中のコードを見たときにそのようなものを見るかも知れません。 =begin original Here's an example of a module as a blessed scalar: =end original これは bless されたスカラとしてのモジュールの例です: package Time; use strict; use warnings; sub new { my $class = shift; my $time = time; return bless \$time, $class; } sub epoch { my $self = shift; return ${ $self }; } my $time = Time->new(); print $time->epoch(); =head2 Inside-Out objects (インサイドアウトオブジェクト) =begin original In the past, the Perl community experimented with a technique called "inside-out objects". An inside-out object stores its data outside of the object's reference, indexed on a unique property of the object, such as its memory address, rather than in the object itself. This has the advantage of enforcing the encapsulation of object attributes, since their data is not stored in the object itself. =end original 過去に、Perl コミュニティは「インサイドアウトオブジェクト」と呼ばれる テクニックを実験しました。 インサイドアウトオブジェクトは、そのデータをオブジェクト自身ではなく、 そのメモリアドレスのようなオブジェクトのユニークな属性をインデックスとして、 オブジェクトのリファレンスの外側に保管します。 これは、オブジェクトの属性のカプセル化を強制するという利点があります; なぜならそれらのデータはオブジェクト自身に保管されないからです。 =begin original This technique was popular for a while (and was recommended in Damian Conway's I), but never achieved universal adoption. The L module on CPAN provides a comprehensive implementation of this technique, and you may see it or other inside-out modules in the wild. =end original このテクニックはしばらくの間人気があり (そして Damian Conway の I で推奨され) ましたが、 一般的な採用を達成することはありませんでした。 CPAN の L モジュールはこのテクニックの包括的な 実装を提供し、世の中ではこれやその他のインサイドアウトモジュールを 見かけるかも知れません。 =begin original Here is a simple example of the technique, using the L core module. This module was added to the core to support inside-out object implementations. =end original これは L コアモジュールを使ったこのテクニックの 簡単な例です。 このモジュールはインサイドアウトオブジェクト実装に対応するために コアに追加されました。 package Time; use strict; use warnings; use Hash::Util::FieldHash 'fieldhash'; fieldhash my %time_for; sub new { my $class = shift; my $self = bless \( my $object ), $class; $time_for{$self} = time; return $self; } sub epoch { my $self = shift; return $time_for{$self}; } my $time = Time->new; print $time->epoch; =head2 Pseudo-hashes (疑似ハッシュ) =begin original The pseudo-hash feature was an experimental feature introduced in earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an array reference which can be accessed using named keys like a hash. You may run in to some code in the wild which uses it. See the L pragma for more information. =end original 疑似ハッシュ機能は、以前のバージョンの Perl で導入され、 5.10.0 で削除された実験的機能です。 疑似ハッシュは、ハッシュのように名前付きのキーを使ってアクセスされる 配列リファレンスです。 これを使ったコードに出くわすことがあるかも知れません。 さらなる情報については L プラグマを参照してください。 =head1 SEE ALSO =begin original A kinder, gentler tutorial on object-oriented programming in Perl can be found in L. You should also check out L for some style guides on constructing both modules and classes. =end original Perl でのオブジェクト指向プログラミングに関するより親切で優しい チュートリアルは L にあります。 また、モジュールとクラスの両方を構築するためのスタイルガイドについて L をチェックするべきです。 =begin meta Translate: SHIRAKATA Kentaro Status: completed =end meta