5.38.0

NAME

perlobj - Perl object reference

perlobj - Perl オブジェクトのリファレンス

説明

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 perlootut.

この文書は、Perl のオブジェクト指向機能のリファレンスを提供します。 Perl でのオブジェクト指向プログラミングの概要を探しているなら、 perlootut を参照してください。

In order to understand Perl objects, you first need to understand references in Perl. See perlreftut for details.

Perl のオブジェクトを理解するためには、まず Perl のリファレンスを 理解する必要があります。 詳しくは perlreftut を参照してください。

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 perlootut.

この文書は Perl のオブジェクト指向 (OO) 機能の全てを一から記述しています。 単に自分自身でオブジェクト指向のコードを書く方法を探しているなら、 おそらく CPAN から perlootut に記述されているオブジェクトシステムの 一つを使うことによってよりよく扱えるでしょう。

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.

自分自身のオブジェクトシステムの書き方を探していたり、 一からオブジェクトを実装しているコードを保守する必要があるなら、 この文書はどうやって Perl がオブジェクト指向を行っているかを正確に 理解する助けになるでしょう。

There are a few basic principles which define object oriented Perl:

オブジェクト指向 Perl を定義するいくつかの基本的な原則があります:

  1. An object is simply a data structure that knows to which class it belongs.

    オブジェクトは単に、どのクラスに属するかを知っているデータ構造です。

  2. A class is simply a package. A class provides methods that expect to operate on objects.

    クラスは単にパッケージです。 クラスはオブジェクトを操作することを想定したメソッドを提供します。

  3. A method is simply a subroutine that expects a reference to an object (or a package name, for class methods) as the first argument.

    メソッドは単に、最初の引数としてオブジェクト (またはクラスメソッドの場合は パッケージ名) を想定するサブルーチンです。

Let's look at each of these principles in depth.

それぞれの原則を深く見てみましょう。

オブジェクトは単なるデータ構造

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.

オブジェクト指向に対応しているその他の多くの言語と違って、 Perl はオブジェクトを構築するための特別な文法を提供していません。 オブジェクトは、特定のクラスと明示的に関連付けられている 単なる Perl データ構造(ハッシュ、配列、スカラ、ファイルハンドルなど)です。

That explicit association is created by the built-in bless function, which is typically used within the constructor subroutine of the class.

明示的な関連付けは組み込みの bless 関数によって作られます; これは典型的にはクラスの コンストラクタ サブルーチンの中で使われます。

Here is a simple constructor:

以下は単純なコンストラクタです:

  package File;

  sub new {
      my $class = shift;

      return bless {}, $class;
  }

The name new isn't special. We could name our constructor something else:

new という名前は特別ではありません。 コンストラクタに他の名前を付けることも出来ます:

  package File;

  sub load {
      my $class = shift;

      return bless {}, $class;
  }

The modern convention for OO modules is to always use new 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.

OO モジュールのモダンな慣習は、コンストラクタの名前として 常に new を使うというものですが、そうする必要性はありません。 データ構造をクラスに bless するどんなサブルーチンも Perl での 正当なコンストラクタです。

In the previous examples, the {} code creates a reference to an empty anonymous hash. The bless function then takes that reference and associates the hash with the class in $class. In the simplest case, the $class variable will end up containing the string "File".

前述の例で、{} というコードは、空の無名ハッシュへのリファレンスを 作ります。 それから bless 変数はこのリファレンスを取り、ハッシュを $class のクラスと関連付けます。 最も単純な場合では、$class 変数は "File" という文字列を含んでいます。

We can also use a variable to store a reference to the data structure that is being blessed as our object:

また、オブジェクトとして bless するデータ構造へのリファレンスを補完する 変数を使うことも出来ます:

  sub new {
      my $class = shift;

      my $self = {};
      bless $self, $class;

      return $self;
  }

Once we've blessed the hash referred to by $self we can start calling methods on it. This is useful if you want to put object initialization in its own separate method:

$self で参照されているハッシュを bless すれば、 それに含まれるメソッドを呼び出し始められます。 オブジェクトの初期化を独自の分離されたメソッドで行いたい場合に これは有用です:

  sub new {
      my $class = shift;

      my $self = {};
      bless $self, $class;

      $self->_initialize();

      return $self;
  }

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 encapsulation. 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.

オブジェクトはハッシュでもあるので、これをハッシュとして扱うことが出来、 オブジェクトに関連付けられているデータを保管するのに使えます。 典型的には、クラス内のコードはハッシュをアクセス可能なデータ構造として 扱い、クラスの外側のコードは常にオブジェクトを不透明なものとして 扱うべきです。 これは カプセル化 と呼ばれます。 カプセル化とは、オブジェクトのユーザーはそれがどのように実装されているかを 知る必要がないということです。 ユーザーは単にオブジェクトの文書化されたメソッドを呼び出します。

Note, however, that (unlike most other OO languages) Perl does not ensure or enforce encapsulation in any way. If you want objects to actually be opaque you need to arrange for that yourself. This can be done in a variety of ways, including using "Inside-Out objects" or modules from CPAN.

しかし、(その他の OO 言語のほとんどと違って) Perl はなんらかの方法で カプセル化を保証したり強制したりしません。 もしあなたがオブジェクトを本当に不透明に する ことを望むなら、 あなた自身でそうなるように準備する必要があります。 これをするには、"Inside-Out objects"" in " や CPAN のモジュールを使うことを 含めて様々な方法があります。

オブジェクトは bless されている; 変数はされていない

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 referent). This is best demonstrated with this code:

私たちが何かを bless するとき、 私たちはそのものへのリファレンスを含んでいる変数を bless しているのではなく、 変数に保管されているリファレンスを bless しているのでもありません; 私たちは変数が参照している何か(時々 参照先 (referent) として知られます) を bless しています。 これはこのコードで最も良く表されています:

  use Scalar::Util 'blessed';

  my $foo = {};
  my $bar = $foo;

  bless $foo, 'Class';
  print blessed( $bar ) // 'not blessed';    # prints "Class"

  $bar = "some other value";
  print blessed( $bar ) // 'not blessed';    # prints "not blessed"

When we call bless 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 blessed( $bar ) returns false. At that point $bar is no longer storing a reference to an object.

変数に対して bless を呼び出すと、実際には変数が参照している 基となるデータ構造を bless しています。 リファレンス自身や、リファレンスを保管している変数を bless しているのでは ありません。 これが、2 番目の blessed( $bar ) が偽を返す理由です。 この時点では $bar はもはやオブジェクトへのリファレンスを 保管していません。

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).

時々古い本や文書で「リファレンスを bless する」という記述や、 オブジェクトのことを「bless されたリファレンス」と説明しているのを 見るかも知れませんが、これは不正確です。 bless されたリファレンスがオブジェクトなのではありません; リファレンスが参照しているもの (つまり参照先) です。

クラスは単なるパッケージ

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 don't operate on an object or class.

Perl はクラス定義のための特別な文法を提供しません。 パッケージは変数とサブルーチンを含む単なる名前空間です。 クラスとの唯一の違いは、サブルーチンはその最初の引数に オブジェクトへのリファレンスかクラス名を想定すると言うことです。 これは純粋に規約の問題なので、一つのクラスにメソッドと、オブジェクトや クラスを操作 しない サブルーチンの両方を含むことも出来ます。

Each package contains a special array called @ISA. The @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.

各パッケージは @ISA と呼ばれる特別な配列を持ちます。 @ISA 配列は (もしあれば) そのクラスの親クラスの一覧からなります。 この配列は、後述する、Perl がメソッド解決をするときにチェックされます。

Calling methods from a package means it must be loaded, of course, so you will often want to load a module and add it to @ISA at the same time. You can do so in a single step using the parent pragma. (In older code you may encounter the base pragma, which is nowadays discouraged except when you have to work with the equally discouraged fields pragma.)

パッケージからのメソッド呼び出しは、もちろん それを読み込まなければならないということなので、 しばしばモジュールを読み込んでそれを同時に @ISA に追加したいでしょう。 parent を使って 1 ステップでそうできます。 (古いコードでは base プラグマに遭遇するかもしれません; これは最近では同様に非推奨の fields プラグマと共に動作するのでない限り 非推奨です。)

However the parent classes are set, the package's @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.

しかし、親クラスが設定されると、そのパッケージの @ISA 変数は それらの親のリストになります。 これは単純にスカラのリストで、それぞれはパッケージ名に対応する 文字列です。

All classes inherit from the UNIVERSAL class implicitly. The UNIVERSAL class is implemented by the Perl core, and provides several default methods, such as isa(), can(), and VERSION(). The UNIVERSAL class will never appear in a package's @ISA variable.

全てのクラスは暗黙に UNIVERSAL クラスから継承されます。 UNIVERSAL クラスは Perl コアによって実装されていて、 isa(), can(), and VERSION() のようないくつかのデフォルトメソッドを 提供します。 UNIVERSAL クラスは 決して パッケージの @ISA 変数に表れません。

Perl only provides method inheritance as a built-in feature. Attribute inheritance is left up the class to implement. See the "Writing Accessors" section for details.

Perl は組み込み機能としてメソッド継承 のみ を提供します。 属性継承は実装されるクラスに残されています。 詳しくは "Writing Accessors" 節を参照してください。

メソッドは単なるサブルーチン

Perl does not provide any special syntax for defining a method. A method is simply a regular subroutine, and is declared with sub. What makes a method special is that it expects to receive either an object or a class name as its first argument.

Perl はメソッドを定義するための特別な文法を提供しません。 メソッドは単に通常のサブルーチンで、sub によって宣言されます。 メソッドを特別にしているのは、それが最初の引数として オブジェクトかクラス名を受け取ることを想定していると言うことです。

Perl does provide special syntax for method invocation, the -> operator. We will cover this in more detail later.

Perl には -> 演算子というメソッド起動のための特別な文法が あります。 後にこれに関する詳細を取り上げます。

Most methods you write will expect to operate on objects:

あなたの書くほとんどのメソッドはオブジェクトを操作することを想定します:

  sub save {
      my $self = shift;

      open my $fh, '>', $self->path() or die $!;
      print {$fh} $self->data()       or die $!;
      close $fh                       or die $!;
  }

メソッドの起動

Calling a method on an object is written as $object->method.

オブジェクトのメソッドの呼び出しは $object->method のように書けます。

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.

メソッド起動 (つまり矢印) 演算子の左側はオブジェクト(またはメソッド名)で、 右側はメソッド名です。

  my $pod = File->new( 'perlobj.pod', $data );
  $pod->save();

The -> syntax is also used when dereferencing a reference. It looks like the same operator, but these are two different operations.

-> 文法は、リファレンスをデリファレンスするためにも使われます。 これは同じ演算子のように見えますが、これらは二つの異なった処理です。

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 Critter->new(), the new() method receives the string "Critter" as its first argument. When we call $fred->speak(), the $fred variable is passed as the first argument to speak().

メソッドを呼び出すとき、矢印の左側のものがメソッドの最初の引数として 渡されます。 つまり、Critter->new() を呼び出すと、 new() メソッドは最初の引数として文字列 "Critter" を受け取ります。 $fred->speak() を呼び出すと、 $fred 変数が speak() の最初の引数として渡されます。

Just as with any Perl subroutine, all of the arguments passed in @_ are aliases to the original argument. This includes the object itself. If you assign directly to $_[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.

他の Perl のサブルーチンと同様、@_ で渡される全ての引数は 元の引数への別名です。 これにはオブジェクト自身も含まれます。 $_[0] に直接代入すると、オブジェクトへのリファレンスを 保持している変数の内容を変更します。 あなたが何をしているのかを正確に分かっていない限り、 これをしないことを勧めます。

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.

Perl は、矢印の左側を見ることで、メソッドがどのパッケージにあるかを知ります。 左側がパッケージ名なら、そのパッケージのメソッドを探します。 左側がオブジェクトなら、Perl はオブジェクトに bless されている パッケージのメソッドを探します。

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 "Method Call Variations" for more nuances.

左側がパッケージ名でもオブジェクトでもない場合、メソッド呼び出しは エラーになりますが、さらなるニュアンスについては "Method Call Variations" の説を参照してください。

継承

We already talked about the special @ISA array and the parent pragma.

特別な @ISA 配列と parent プラグマについては既に話しました。

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.

あるクラスが他のクラスを継承すると、親クラスで定義されているどのメソッドも 子クラスで利用可能です。 あるオブジェクトで自分自身のクラスで定義されていないメソッドを 呼び出そうとすると、Perl は親クラスにあるメソッドも探します。

  package File::MP3;
  use parent 'File';    # sets @File::MP3::ISA = ('File');

  my $mp3 = File::MP3->new( 'Andvari.mp3', $data );
  $mp3->save();

Since we didn't define a save() method in the File::MP3 class, Perl will look at the File::MP3 class's parent classes to find the save() method. If Perl cannot find a save() method anywhere in the inheritance hierarchy, it will die.

File::MP3 クラスに save() メソッドを定義していないので、 Perl は save() メソッドを見つけるために File::MP3 クラスの 親クラスを見ます。 Perl が継承階層のどこにも save() メソッドを見つけられないと、 die します。

In this case, it finds a save() method in the File class. Note that the object passed to save() in this case is still a File::MP3 object, even though the method is found in the File class.

この場合、File クラスの save() メソッドを見つけます。 この場合、メソッドは File クラスで見つかったとしても、 save() に渡されるオブジェクトはやはり File::MP3 であることに 注意してください。

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 SUPER pseudo-class.

子クラスのメソッドで親クラスのメソッドをオーバーライドできます。 そうしたとき、SUPER 疑似クラスで親クラスのメソッドを呼び出すことも 出来ます。

  sub save {
      my $self = shift;

      say 'Prepare to rock';
      $self->SUPER::save();
  }

The SUPER modifier can only be used for method calls. You can't use it for regular subroutine calls or class methods:

SUPER 修飾子はメソッド呼び出しで のみ 使えます。 通常のサブルーチン呼び出しやクラスメソッドでは使えません:

  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

SUPER はどのように解決されるか

The SUPER pseudo-class is resolved from the package where the call is made. It is not 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.

SUPER 疑似クラスは、呼び出しが行われたパッケージから解決されます。 これはオブジェクトのクラスを元にして解決 されません 。 これは重要です; なぜならこれにより 深い継承階層でそれぞれ異なったレベルにあるメソッドが それぞれの親メソッドを正しく呼び出せるようになるからです。

  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();

In this example, we will get the following output:

この例では、次のような出力になります:

  A
  B
  C

This demonstrates how SUPER is resolved. Even though the object is blessed into the C class, the speak() method in the B class can still call SUPER::speak() and expect it to correctly look in the parent class of B (i.e the class the method call is in), not in the parent class of C (i.e. the class the object belongs to).

これはどのように SUPER が解決されるかを図示します。 たとえオブジェクトが C クラスに bless されていても、 B クラスの speak() メソッドはまだ SUPER::speak() を呼び出して、正しく B (つまりメソッド呼び出しされた クラス)の親クラスを見ることを想定します; C (つまりオブジェクトが属するクラス) の親クラスではありません。

There are rare cases where this package-based resolution can be a problem. If you copy a subroutine from one package to another, SUPER resolution will be done based on the original package.

このパッケージを基にした解決が問題になる稀な場合があります。 サブルーチンをあるパッケージから他にコピーすると、 SUPER の解決は元のパッケージを基にして行われます。

多重継承

Multiple inheritance often indicates a design problem, but Perl always gives you enough rope to hang yourself with if you ask for it.

多重継承はしばしば設計上の問題を表しますが、しかしあなたが求めるなら、 Perl は常にあなた自身がぶら下がるのに十分なロープを与えます。

To declare multiple parents, you simply need to pass multiple class names to use parent:

多重継承を宣言するには、 単に複数のクラス名を use parent に渡す必要があります:

  package MultiChild;

  use parent 'Parent1', 'Parent2';

メソッド解決順序

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:

メソッド解決順序は多重継承の場合にのみ問題になります。 単一継承の場合は、Perl はメソッドを見つけるために単純に継承チェーンを 探します:

  Grandparent
    |
  Parent
    |
  Child

If we call a method on a Child object and that method is not defined in the Child class, Perl will look for that method in the Parent class and then, if necessary, in the Grandparent class.

Child オブジェクトのメソッドを呼び出して、そのメソッドが Child クラスに定義されていない場合、 Perl はParent クラスのメソッドを探し、 それからもし必要なら Grandparent クラスを探します。

If Perl cannot find the method in any of these classes, it will die with an error message.

Perl がこれらのクラスのどこからもこのメソッドを見つけられない場合、 エラーメッセージと共に die します。

When a class has multiple parents, the method lookup order becomes more complicated.

クラスが複数の親を持つとき、メソッド検索順序はより複雑になります。

By default, Perl does a depth-first left-to-right search for a method. That means it starts with the first parent in the @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 @ISA array and searches from there.

デフォルトでは、Perl はメソッドに対して深さ優先左から右探索を行います。 つまり、@ISA 配列の最初の親から始め、それからその全ての親、祖父母、 というように探索します。 メソッドを見つけることに失敗すると、元のクラスの @ISA 配列の 次の親に行き、そこから探索します。

            SharedGreatGrandParent
            /                    \
  PaternalGrandparent       MaternalGrandparent
            \                    /
             Father        Mother
                   \      /
                    Child

So given the diagram above, Perl will search Child, Father, PaternalGrandparent, SharedGreatGrandParent, Mother, and finally MaternalGrandparent. This may be a problem because now we're looking in SharedGreatGrandParent before we've checked all its derived classes (i.e. before we tried Mother and MaternalGrandparent).

従って、前述した図の場合、Perl は Child, Father, PaternalGrandparent, SharedGreatGrandParent, Mother そして最後に MaternalGrandparent を探索します。 これは SharedGreatGrandParent クラスを、その全ての派生クラスを チェックする (つまり MotherMaternalGrandparent を試す) 前に 見るので、問題があるかも知れません。

It is possible to ask for a different method resolution order with the mro pragma.

mro プラグマで異なったメソッド解決順序を使うようにすることができます。

  package Child;

  use mro 'c3';
  use parent 'Father', 'Mother';

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: Child, Father, PaternalGrandparent, Mother MaternalGrandparent, and finally SharedGreatGrandParent. Note however that this is not "breadth-first" searching: All the Father ancestors (except the common ancestor) are searched before any of the Mother ancestors are considered.

このプラグマは "C3" 解決順序に切り替えます。 簡単に言えば、"C3" 順序は 共有親クラスが子クラスより先に探索されないことを保証するので、 Perl は次の順で探索するようになります: Child, Father, PaternalGrandparent, Mother MaternalGrandparent そして最後に SharedGreatGrandParent。 しかし、これは「幅優先」探索ではないことに注意してください: (共通の祖先を除く) 全ての Father の祖先は、 Mother の祖先より前に探索されます。

The C3 order also lets you call methods in sibling classes with the next pseudo-class. See the mro documentation for more details on this feature.

C3 順序はまた、next 疑似クラスで兄弟クラスのメソッドを 呼び出せるようにします。 この機能に関するさらなる詳細については mro 文書を参照してください。

メソッド解決キャッシュ

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.

Perl がメソッドを探すとき、結果をキャッシュするので、 そのメソッドを将来呼び出しても再び探す必要はありません。 クラスの親クラスが変更されたり、クラスにサブルーチンが追加されると、 そのクラスのキャッシュは無効化されます。

The mro pragma provides some functions for manipulating the method cache directly.

mro プラグマはメソッドキャッシュを直接操作するための いくつかの関数を提供します。

コンストラクタを書く

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.

前述したように、Perl はコンストラクタのための特別な文法を提供しません。 つまり、クラスは自身のコンストラクタを実装しなければなりません。 コンストラクタは新しいオブジェクトへのリファレンスを返す単なる クラスメソッドです。

The constructor can also accept additional parameters that define the object. Let's write a real constructor for the File class we used earlier:

コンストラクタはまた、オブジェクトを定義するための追加の引数を受け取れます。 以前に使った File クラスの実際のコンストラクタを書いてみましょう:

  package File;

  sub new {
      my $class = shift;
      my ( $path, $data ) = @_;

      my $self = bless {
          path => $path,
          data => $data,
      }, $class;

      return $self;
  }

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.

ここで見られるように、パスとファイルデータをオブジェクト自身に 保管しています。 水面下では、このオブジェクトはまだ単なるハッシュであることを 忘れないでください。 後で、このデータを操作するためのアクセサを書きます。

For our File::MP3 class, we can check to make sure that the path we're given ends with ".mp3":

この 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(@_);
  }

This constructor lets its parent class do the actual object construction.

このコンストラクタは親クラスに実際のオブジェクト構築を行わせます。

属性

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.

属性は特定のオブジェクトに所属するデータ片です。 ほとんどのオブジェクト指向言語と異なり、Perl は属性の宣言や操作に 対応する特別な文法を提供しません。

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.

属性はしばしばオブジェクト自身に保管されます。 例えば、オブジェクトが無名ハッシュなら、属性名をキーとして使って そのハッシュに属性値を保管できます。

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.

これらのハッシュキーをクラスの外側から直接参照することは可能ですが、 全ての属性へのアクセスをアクセサメソッドで包むのがベストプラクティスと 考えられています。

This has several advantages. Accessors make it easier to change the implementation of an object later while still preserving the original API.

これにはいくつかの利点があります。 アクセサは、後に元の API を保存したままオブジェクトの実装を 変更するのをより簡単にします。

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.

アクセサは属性アクセスに関する追加のコードを追加できるようにします。 例えば、コンストラクタで設定されない属性のデフォルトを適用したり、 属性の新しい値が受け入れられるかの検証をしたり出来ます。

Finally, using accessors makes inheritance much simpler. Subclasses can use the accessors rather than having to know how a parent class is implemented internally.

最後に、アクセサを使うと継承が遙かに簡単になります。 サブクラスはアクセサを使うことで、親クラスが内部でどのように 実装されているかを知る必要がなくなります。

アクセサを書く

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.

コンストラクタと同様、Perl は特別なアクセサ宣言文法を持たないので、 クラスは明示的に書かれたアクセサメソッドを提供しなければなりません。 アクセサには 2 種類あります; 読み込み専用と読み書き用です。

A simple read-only accessor simply gets the value of a single attribute:

単純な読み込み専用アクセサは単純に単一の属性の値を取得します:

  sub path {
      my $self = shift;

      return $self->{path};
  }

A read-write accessor will allow the caller to set the value as well as get it:

読み書きアクセサは、呼び出し側が取得と共に値の設定もできるようにします:

  sub path {
      my $self = shift;

      if (@_) {
          $self->{path} = shift;
      }

      return $self->{path};
  }

より賢く安全なコードのための余談

Our constructor and accessors are not very smart. They don't check that a $path is defined, nor do they check that a $path is a valid filesystem path.

このコンストラクタとアクセサはあまり賢くありません。 $path が定義されているかをチェックしませんし、 $path が有効なファイルシステムパスかをチェックしません。

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 perlootut.

これらのチェックを手で書くのはすぐに退屈になります。 たくさんのアクセサを手で書くのもとても退屈です。 より安全でより簡潔なコードを書くことを助けるための、 perlootut で推奨されているモジュールを含む多くのモジュールが CPAN にあります。

メソッド呼び出しのバリエーション

Perl supports several other ways to call methods besides the $object->method() usage we've seen so far.

Perl には $object->method() という使用法以外にもメソッドを呼び出す 方法がいくつかあるのでそれを見ていきます。

完全修飾名付きのメソッド名

Perl allows you to call methods using their fully qualified name (the package and method name):

Perl はメソッドをその完全修飾名(パッケージ名とメソッド名)を使って 呼び出すことを許します:

  my $mp3 = File::MP3->new( 'Regin.mp3', $data );
  $mp3->File::save();

When you call a fully qualified method name like File::save, the method resolution search for the save method starts in the File class, skipping any save method the File::MP3 class may have defined. It still searches the File class's parents if necessary.

File::save のような完全修飾メソッド名を使った場合、 save メソッドのためのメソッド解決探索は File クラスから始め、File::MP3 クラスが定義しているかも知れない save メソッドは飛ばされます。 必要があれば File クラスの親クラスは探索されます。

While this feature is most commonly used to explicitly call methods inherited from an ancestor class, there is no technical restriction that enforces this:

この機能は祖先クラスから継承されたメソッドを明示的に呼ぶために 使われるのがもっとも一般的ですが、それに限定する技術的な制限はありません:

  my $obj = Tree->new();
  $obj->Dog::bark();

This calls the bark method from class Dog on an object of class Tree, even if the two classes are completely unrelated. Use this with great care.

この呼び出しは、たとえ二つのクラスが完全に無関係でも、 Tree クラスのオブジェクトで Dog クラスの bark メソッドを呼び出します。 これはとても注意して使ってください。

The SUPER pseudo-class that was described earlier is not the same as calling a method with a fully-qualified name. See the earlier "Inheritance" section for details.

前述した SUPER 疑似クラスは完全修飾名でのメソッド呼び出しと 同じ ではありません 。 詳しくは前述した "Inheritance" の節を参照してください。

文字列としてのメソッド名

Perl lets you use a scalar variable containing a string as a method name:

Perl は文字列を含むスカラ変数をメソッド名として使うことを許しています:

  my $file = File->new( $path, $data );

  my $method = 'save';
  $file->$method();

This works exactly like calling $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.

これは正確に $file->save() 呼び出しと同様です。 これは動的コードを書くのにとても有用です。 例えば、他のメソッドの引数として呼び出されるメソッド名を渡せるようになります。

文字列としてのクラス名

Perl also lets you use a scalar containing a string as a class name:

Perl は文字列を含むスカラをクラス名として使うことを許しています:

  my $class = 'File';

  my $file = $class->new( $path, $data );

Again, this allows for very dynamic code.

再び、これによりとても動的なコードが書けます。

メソッドとしてのサブルーチンリファレンス

You can also use a subroutine reference as a method:

サブルーチンリファレンスをメソッドとして使うことも出来ます:

  my $sub = sub {
      my $self = shift;

      $self->save();
  };

  $file->$sub();

This is exactly equivalent to writing $sub->($file). You may see this idiom in the wild combined with a call to can:

これは $sub->($file) と書くのと正確に等価です。 世の中ではこの慣用句を can の呼び出しと結びつけられているのを 見ることがあるでしょう:

  if ( my $meth = $object->can('foo') ) {
      $object->$meth();
  }

メソッド呼び出しのデリファレンス

Perl also lets you use a dereferenced scalar reference in a method call. That's a mouthful, so let's look at some code:

Perl はまた、メソッド呼び出しの中でデリファレンスされたスカラリファレンスを 使うことを許しています。 これは分かりにくいので、コードを見てください:

  $file->${ \'save' };
  $file->${ returns_scalar_ref() };
  $file->${ \( returns_scalar() ) };
  $file->${ returns_ref_to_sub_ref() };

This works if the dereference produces a string or a subroutine reference.

これは、デリファレンスが文字列 または サブルーチンリファレンスを 生成するときに動作します。

ファイルハンドルでのメソッド呼び出し

Under the hood, Perl filehandles are instances of the IO::Handle or IO::File class. Once you have an open filehandle, you can call methods on it. Additionally, you can call methods on the STDIN, STDOUT, and STDERR filehandles.

水面下では、Perl のファイルハンドルは IO::Handle または IO::File クラスのインスタンスです。 一度ファイルハンドルを開くと、そのメソッドを呼び出せます。 さらに、STDIN, STDOUT, STDERR ファイルハンドルのメソッドを 呼び出せます。

  open my $fh, '>', 'path/to/file';
  $fh->autoflush();
  $fh->print('content');

  STDOUT->autoflush();

クラスメソッドの起動

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 Class->new() can be interpreted as either 'Class'->new() or 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 Class() in the current namespace, Perl will always interpret Class->new() as the second alternative: a call to new() on the object returned by a call to Class()

Perl はパッケージ名とサブルーチン名に裸の単語を使うことを許しているので、 時々裸の単語の意味を誤って解釈します。 例えば、Class->new() という構文は、 'Class'->new() または Class()->new() のどちらでも解釈できます。 英語では、2 番目の解釈は「Class() という名前のサブルーチンを呼び出し、 それから Class() の返り値のメソッドとして new() を呼び出す」と読めます。 現在の名前空間に Class() という名前のサブルーチンがある場合、 Perl は常に Class->new() を 2 番目の選択肢のように解釈します: Class() から返されたオブジェクトの new() を呼び出します。

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 :: to the class name:

二つの方法で最初の解釈 (つまり "Class" というクラスのメソッド呼び出し) を Perl に強制できます。 まず、:: をクラス名に追加できます:

    Class::->new()

Perl will always interpret this as a method call.

Perl は常にこれをメソッド呼び出しとして解釈します。

Alternatively, you can quote the class name:

あるいは、クラス名をクォートできます:

    'Class'->new()

Of course, if the class name is in a scalar Perl will do the right thing as well:

もちろん、クラス名がスカラであれば Perl は同様に正しいことを行います:

    my $class = 'Class';
    $class->new();

間接オブジェクト文法

Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl interpreter. See below for more details.

ファイルハンドルの場合を除いて、この文法の使用は非推奨です; Perl インタプリタを混乱させることがあるからです。 さらなる詳細については以降を参照してください。

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.

Perl は、「間接オブジェクト」記法と呼ばれるもう一つのメソッド起動文法に 対応しています。 この文法は、起動されるオブジェクトの前にメソッド名が来るので 「間接」と呼ばれます。

This syntax can be used with any class or object method:

この文法は任意のクラスおよびオブジェクトメソッドで使えます:

    my $file = new File $path, $data;
    save $file;

We recommend that you avoid this syntax, for several reasons.

いくつかの理由により、この文法は避けることを勧めます。

First, it can be confusing to read. In the above example, it's not clear if save is a method provided by the File class or simply a subroutine that expects a file object as its first argument.

まず、これは読むのに混乱することがあります。 前述の例では、saveFile によって提供されるメソッドなのか 最初の引数としてファイルオブジェクトを想定する単なるサブルーチンなのかが はっきりしません。

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 File->new( $path, $data ) or new( File( $path, $data ) ).

クラスメソッドで使うとき、問題はさらに悪くなります。 Perl はサブルーチン名を裸の単語として書くことを許しているので、 メソッドの後の裸の単語がクラス名なのかサブルーチン名なのかを Perl が推測する必要があります。 言い換えると、Perl はこの文法を File->new( $path, $data ) あるいは new( File( $path, $data ) ) と解釈できます。

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!

このコードをパースするために、 Perl はどんなパッケージ名が見られるか、どんなサブルーチンが現在の パッケージに存在するか、どんな裸の単語が以前に見られたか、 およびその他の入力を元にした経験則を使います。 言うまでもなく、経験則はとても驚く結果を招くことがあります!

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.

より古い文書 (およびいくつかの CPAN モジュール) では、 特にコンストラクタについて、この文法を推奨していたので、 まだ世の中でこれを見ることがあるかもしれません。 しかし、新しいコードにこれを使うことは避けることを推奨します。

You can force Perl to interpret the bareword as a class name by appending "::" to it, like we saw earlier:

以前に見たように、クラス名に "::" を付けることで、Perl が裸の単語として 解釈することを強制できます:

  my $file = new File:: $path, $data;

Indirect object syntax is only available when the "indirect" named feature is enabled. This is enabled by default, but can be disabled if requested. This feature is present in older feature version bundles, but was removed from the :5.36 bundle; so a use VERSION declaration of v5.36 or above will also disable the feature.

間接オブジェクト構文は、 "indirect" という名前の機能が 有効の場合にのみ利用可能です。 これはデフォルトでは有効ですが、要求されれば無効にできます。 この機能は古い機能の束には含まれていますが、 :5.36 の束からは 削除されました; 従って、v5.36 またはそれ以上の use VERSION 宣言をしても、 この機能は無効になります。

    use v5.36;
    # indirect object syntax is no longer available

bless, blessed, and ref

(bless, blessed, ref)

As we saw earlier, an object is simply a data structure that has been blessed into a class via the bless function. The bless function can take either one or two arguments:

既に見たように、オブジェクトは bless 関数でクラスに bless された 単なるデータ構造です。 bless 関数は一つまたは二つの引数を取ります:

  my $object = bless {}, $class;
  my $object = bless {};

In the first form, the anonymous hash is being blessed into the class in $class. In the second form, the anonymous hash is blessed into the current package.

1 番目の形式では、無名ハッシュは $class のクラスに bless されます。 2 番目の形式では、無名ハッシュは現在のパッケージに bless されます。

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.

2 番目の形式は強く非推奨です; なぜならこれは親のコンストラクタを 再利用するサブクラスの能力を壊すからです; しかし既に存在しているコードではまだこれを見ることがあるでしょう。

If you want to know whether a particular scalar refers to an object, you can use the blessed function exported by Scalar::Util, which is shipped with the Perl core.

あるスカラがオブジェクトを参照しているかどうかを知りたい場合、 Perl コアと同梱されている Scalar::Util からエクスポートされている blessed 関数が使えます。

  use Scalar::Util 'blessed';

  if ( defined blessed($thing) ) { ... }

If $thing refers to an object, then this function returns the name of the package the object has been blessed into. If $thing doesn't contain a reference to a blessed object, the blessed function returns undef.

$thing がオブジェクトを参照しているなら、この関数はオブジェクトが bless されているパッケージ名を返します。 $thing が bless されたオブジェクトへのリファレンスを含んでいないなら、 blessed 関数は undef を返します。

Note that blessed($thing) will also return false if $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.

$thing が "0" という名前のクラスに bless されている場合も blessed($thing) は偽を返すことに注意してください。 これは可能ですが、かなり極端です。 何をしているか分かっていない限り、"0" という名前のクラスを 作らないでください。

Similarly, Perl's built-in ref function treats a reference to a blessed object specially. If you call ref($thing) and $thing holds a reference to an object, it will return the name of the class that the object has been blessed into.

同様に、Perl の組み込みの ref 関数は bless されたオブジェクトへの リファレンスを特別に扱います。 ref($thing) を呼び出して、$thing がオブジェクトへのリファレンスを 保持している場合、これはオブジェクトが bless されているクラス名を返します。

If you simply want to check that a variable contains an object reference, we recommend that you use defined blessed($object), since ref returns true values for all references, not just objects.

単純にある変数がオブジェクトリファレンスを含んでいるかをチェックしたい場合、 defined blessed($object) を使うことを勧めます; ref はオブジェクトだけでなく全てのリファレンスに関して真の値を 返すからです。

UNIVERSAL クラス

All classes automatically inherit from the UNIVERSAL 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.

全てのクラスは、Perl コアに組み込まれている UNIVERSAL クラスから 継承されます。 このクラスは、全てクラスまたはオブジェクトから呼ばれる いくつかのメソッドを提供します。 また、自身のクラスでこれらのメソッドのいくつかを オーバーライドすることを選ぶことも出来ます。 そうする場合は、後述する組み込みの意味論に従うことを勧めます。

isa($class)

The isa method returns true if the object is a member of the class in $class, or a member of a subclass of $class.

isa メソッドは、オブジェクトが $class のクラスか、$class の サブクラスの場合に を返します。

If you override this method, it should never throw an exception.

このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。

DOES($role)

The DOES method returns true if its object claims to perform the role $role. By default, this is equivalent to isa. This method is provided for use by object system extensions that implement roles, like Moose and Role::Tiny.

DOES メソッドは、オブジェクトがロール $role を実行すると主張している 場合に を返します。 デフォルトでは、これは isa と等価です。 このメソッドは、Moose and Role::Tiny のように、ロールを実装している オブジェクトシステム拡張によって使われるために提供されています。

You can also override DOES directly in your own classes. If you override this method, it should never throw an exception.

また、自身のクラスで直接 DOES をオーバーライドすることも出来ます。 このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。

can($method)

The can method checks to see if the class or object it was called on has a method named $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 undef is returned.

can メソッドは、呼び出されたクラスまたはオブジェクトが $method という名前のメソッドを持っているかをチェックします。 これはそのクラスおよび全ての親のメソッドをチェックします。 メソッドが存在する場合、サブルーチンへのリファレンスを返します。 存在しなければ undef が返されます。

If your class responds to method calls via AUTOLOAD, you may want to overload can to return a subroutine reference for methods which your AUTOLOAD method handles.

あなたのクラスが AUTOLOAD 経由のメソッド呼び出しに対応する場合、 AUTOLOAD メソッドが扱うメソッドについてサブルーチンリファレンスを 返すように can をオーバーロードした方が良いでしょう。

If you override this method, it should never throw an exception.

このメソッドをオーバーライドする場合、決して例外を投げないように するべきです。

VERSION($need)

The VERSION method returns the version number of the class (package).

VERSION メソッドはクラス (パッケージ) のバージョン番号を返します。

If the $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 $need; it will die if this is not the case. This method is called automatically by the VERSION form of use.

$need 引数が指定された場合、現在のバージョン (パッケージの $VERSION 変数によって定義されているもの) が $need 以上かどうかを チェックします; そうでない場合は die します。 このメソッドは useVERSION 形式によって自動的に呼び出されます。

    use Package 1.2 qw(some imported subs);
    # implies:
    Package->VERSION(1.2);

We recommend that you use this method to access another package's version, rather than looking directly at $Package::VERSION. The package you are looking at could have overridden the VERSION method.

他のパッケージのバージョンにアクセスする場合は、直接 $Package::VERSION を見るのではなくこのメソッドを使うことを勧めます。 見ようとしているパッケージは VERSION メソッドを オーバーライドしているかも知れません。

We also recommend using this method to check whether a module has a sufficient version. The internal implementation uses the version module to make sure that different types of version numbers are compared correctly.

また、あるモジュールのバージョンが十分かどうかをチェックするのに このメソッドを使うことを勧めます。 内部実装は、異なった種類のバージョン番号が正しく比較されるように version モジュールを使います。

AUTOLOAD

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 AUTOLOAD method, that AUTOLOAD method is called instead.

クラスに存在しないメソッドを呼び出すと、Perl は例外を投げます。 しかし、そのクラスまたは親クラスに AUTOLOAD メソッドが定義されていると、代わりに AUTOLOAD メソッドが 呼び出されます。

AUTOLOAD is called as a regular method, and the caller will not know the difference. Whatever value your AUTOLOAD method returns is returned to the caller.

AUTOLOAD は通常のメソッドとして呼び出され、呼び出し元は 違いを知ることは出来ません。 AUTOLOAD メソッドが返した値が呼び出し元に返されます。

The fully qualified method name that was called is available in the $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 strict 'vars', you need to declare it.

呼び出された完全修飾メソッド名はあなたのクラスのパッケージグローバル変数 $AUTOLOAD から利用可能です。 これはグローバルなので、 strict 'vars' の基でパッケージ名接頭辞なしでこれを参照したい場合は、 宣言する必要があります。

  # 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

Without the our $AUTOLOAD declaration, this code will not compile under the strict pragma.

our $AUTOLOAD 宣言なしだと、このコードは strict プラグマの基ではコンパイル出来ません。

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 perlootut for recommendations on OO coding in Perl.

コメントにあるように、これはアクセサを実装するための良い方法ではありません。 これは遅く、はるかに賢すぎます。 しかし、古い Perl コードでアクセサを提供する方法としてこれを 見ることがあるかも知れません。 Perl での OO コーディングの推奨については perlootut を参照してください。

If your class does have an AUTOLOAD method, we strongly recommend that you override can in your class as well. Your overridden can method should return a subroutine reference for any method that your AUTOLOAD responds to.

クラスに AUTOLOAD メソッドがある場合、 can もオーバーライドすることを強く勧めます。 オーバーライドされた can メソッドは、AUTOLOAD が対応する メソッドについてサブルーチンリファレンスを返すべきです。

デストラクタ

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.

オブジェクトへの最後のリファレンスがなくなると、オブジェクトは破壊されます。 オブジェクトへの一つのリファレンスをレキシカルなスカラに入れているだけの 場合、スカラがスコープ外に出るとオブジェクトは破壊されます。 オブジェクトをパッケージグローバルに保管すると、プログラムが終了するまで オブジェクトはなくならないかもしれません。

If you want to do something when the object is destroyed, you can define a DESTROY method in your class. This method will always be called by Perl at the appropriate time, unless the method is empty.

オブジェクトが破壊されるときに何かをしたい場合、 自分のクラスに DESTROY メソッドを定義できます。 このメソッドは、空でない限り、適切な時点で常に Perl によって呼び出されます。

This is called just like any other method, with the object as the first argument. It does not receive any additional arguments. However, the $_[0] variable will be read-only in the destructor, so you cannot assign a value to it.

これは、他のメソッドと同様、オブジェクトを最初の引数として呼び出されます。 これは追加の引数は受け取りません。 しかし、$_[0] 変数はデストラクタの中では読み込み専用なので、 これに値を代入することは出来ません。

If your DESTROY method throws an exception, this will not cause any control transfer beyond exiting the method. The exception will be reported to STDERR as a warning, marked "(in cleanup)", and Perl will continue with whatever it was doing before.

DESTROY メソッドが例外を投げても、メソッドの終了の先に 制御を移すことはしません。 例外は "(in cleanup)" とマークされた警告として STDERR に報告され、Perl はその前にしていたことを続けます。

Because DESTROY methods can be called at any time, you should localize any global status variables that might be set by anything you do in your DESTROY method. If you are in doubt about a particular status variable, it doesn't hurt to localize it. There are five global status variables, and the safest way is to localize all five of them:

DESTROY メソッドはあらゆる時点で呼び出される可能性があるので、 DESTROY メソッドの中ですることによって設定されるかも知れない全ての グローバル状態変数をローカル化するべきです。 特定の状態変数について疑わしいときは、それをローカル化しても 問題はありません。 グローバル状態変数は五つあるので、最も安全な方法は五つ全てを ローカル化することです:

  sub DESTROY {
      local($., $@, $!, $^E, $?);
      my $self = shift;
      ...;
  }

If you define an AUTOLOAD in your class, then Perl will call your AUTOLOAD to handle the DESTROY method. You can prevent this by defining an empty DESTROY, like we did in the autoloading example. You can also check the value of $AUTOLOAD and return without doing anything when called to handle DESTROY.

クラス内で AUTOLOAD を定義している場合、 Perl は DESTROY メソッドを扱うために AUTOLOAD を呼び出します。 オートロードの例で行ったように、空の DESTROY を定義することによって これを防げます。 また、$AUTOLOAD の値をチェックして、DESTROY を扱うために 呼び出されたときには何もせずに返ることもできます。

グローバルな破壊

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:

プログラムが終了する前のグローバルな破壊の間にオブジェクトが破壊される 順序は予測できません。 つまり、あなたのオブジェクトに含まれているオブジェクトは既に 破壊されているかも知れないということです。 含まれているオブジェクトを呼び出す前にそのメソッドが定義されているかどうかを チェックするべきです:

  sub DESTROY {
      my $self = shift;

      $self->{handle}->close() if $self->{handle};
  }

You can use the ${^GLOBAL_PHASE} variable to detect if you are currently in the global destruction phase:

現在グローバル破壊フェーズ中なのかを検出するために、 ${^GLOBAL_PHASE} 変数が使えます:

  sub DESTROY {
      my $self = shift;

      return if ${^GLOBAL_PHASE} eq 'DESTRUCT';

      $self->{handle}->close();
  }

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 Devel::GlobalDestruction module on CPAN.

この変数は Perl 5.14.0 で追加されたことに注意してください。 より古いバージョンの Perl でグローバル破壊フェーズを検出したい場合は、 CPAN の Devel::GlobalDestruction モジュールを使えます。

If your DESTROY method issues a warning during global destruction, the Perl interpreter will append the string " during global destruction" to the warning.

DESTROY メソッドがグローバルな破壊中に警告を出した場合、 Perl インタプリタは警告に " during global destruction" という文字列を 追加します。

During global destruction, Perl will always garbage collect objects before unblessed references. See "PERL_DESTRUCT_LEVEL" in perlhacktips for more information about global destruction.

グローバルな破壊の間、Perl は常にリファレンスの bless 解除の前に オブジェクトをガベージコレクションします。 グローバルな破壊に関するさらなる情報については "PERL_DESTRUCT_LEVEL" in perlhacktips を参照してください。

非ハッシュオブジェクト

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.

今までの全ての例ではオブジェクトは bless されたハッシュを基にしていました。 しかし、スカラ、グロブ、サブルーチンを含むあらゆる種類のデータ構造や 参照先を bless することが出来ます。 世の中のコードを見たときにそのようなものを見るかも知れません。

Here's an example of a module as a blessed scalar:

これは bless されたスカラとしてのモジュールの例です:

  package Time;

  use v5.36;

  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();

インサイドアウトオブジェクト

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.

過去に、Perl コミュニティは「インサイドアウトオブジェクト」と呼ばれる テクニックを実験しました。 インサイドアウトオブジェクトは、そのデータをオブジェクト自身ではなく、 そのメモリアドレスのようなオブジェクトのユニークな属性をインデックスとして、 オブジェクトのリファレンスの外側に保管します。 これは、オブジェクトの属性のカプセル化を強制するという利点があります; なぜならそれらのデータはオブジェクト自身に保管されないからです。

This technique was popular for a while (and was recommended in Damian Conway's Perl Best Practices), but never achieved universal adoption. The Object::InsideOut module on CPAN provides a comprehensive implementation of this technique, and you may see it or other inside-out modules in the wild.

このテクニックはしばらくの間人気があり (そして Damian Conway の Perl Best Practices で推奨され) ましたが、 一般的な採用を達成することはありませんでした。 CPAN の Object::InsideOut モジュールはこのテクニックの包括的な 実装を提供し、世の中ではこれやその他のインサイドアウトモジュールを 見かけるかも知れません。

Here is a simple example of the technique, using the Hash::Util::FieldHash core module. This module was added to the core to support inside-out object implementations.

これは Hash::Util::FieldHash コアモジュールを使ったこのテクニックの 簡単な例です。 このモジュールはインサイドアウトオブジェクト実装に対応するために コアに追加されました。

  package Time;

  use v5.36;

  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;

疑似ハッシュ

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 fields pragma for more information.

疑似ハッシュ機能は、以前のバージョンの Perl で導入され、 5.10.0 で削除された実験的機能です。 疑似ハッシュは、ハッシュのように名前付きのキーを使ってアクセスされる 配列リファレンスです。 これを使ったコードに出くわすことがあるかも知れません。 さらなる情報については fields プラグマを参照してください。

SEE ALSO

A kinder, gentler tutorial on object-oriented programming in Perl can be found in perlootut. You should also check out perlmodlib for some style guides on constructing both modules and classes.

Perl でのオブジェクト指向プログラミングに関するより親切で優しい チュートリアルは perlootut にあります。 また、モジュールとクラスの両方を構築するためのスタイルガイドについて perlmodlib をチェックするべきです。