名前

perlclass - Perl class syntax reference

perlclass - Perl クラス構文リファレンス

概要

    use v5.38;
    use feature 'class';

    class My::Example 1.234 {
        field $x;

        ADJUST {
            $x = "Hello, world";
        }

        method print_message {
            say $x;
        }
    }

    My::Example->new->print_message;

説明

This document describes the syntax of the Perl's class feature, which provides native keywords supporting object-oriented programming paradigm.

この文書では、オブジェクト指向プログラミングパラダイムをサポートする ネイティブなキーワードを提供する Perl の class 機能の構文について 説明します。

歴史

Since Perl 5, support for objects resolved around the concept of blessing references with a package name. Such reference could then be used to call subroutines from the package it was blessed with (or any of its parents). This system, while bare-bones, was flexible enough to allow creation of multiple more advanced, community-driven systems for object orientation.

Perl 5 以降、オブジェクトのサポートは、パッケージ名によって bless された リファレンスの概念に基づいて解決されました。 このようなリファレンスは、bless されたパッケージ(またはその親のいずれか)から サブルーチンを呼び出すために使えます。 このシステムは、必要最小限のものではありますが、オブジェクト指向のための 複数のより高度な、コミュニティ駆動システムの作成を可能にするのに 十分な柔軟性を備えていました。

Class feature is a core implementation of class syntax which is familiar to what one would find in other programming languages. It isn't a bless wrapper, but a completely new system built right into the perl interpreter.

クラス機能は、他のプログラミング言語で見られるような、クラス構文の コア実装です。 これは bless ラッパーではなく、perl インタプリタに直接組み込まれた 全く新しいシステムです。

キーワード

Enabling the class feature allows the usage of the following new keywords in the scope of current package:

class 機能を有効にすると、現在のパッケージのスコープ内で次の新しい キーワードを使えます。

class

    class NAME BLOCK

    class NAME VERSION BLOCK

    class NAME;

    class NAME VERSION;

The class keyword declares a new package which is intended to be a class. All other keywords from the class feature should be used in scope of this declaration.

class キーワードは、クラスとして意図された新しいパッケージを宣言します。 class機能からの他のすべてのキーワードは、この宣言のスコープ内で 使われる必要があります。

    class WithVersion 1.000 {
        # class definition goes here
    }

Classes can be declared in either block or statement syntax. If a block is used, the body of the block contains the implementation of the class. If the statement form is used, the remainder of the file is used up until the next class or package statement.

クラスは、ブロック構文または文構文のいずれかで宣言できます。 ブロックを使う場合、ブロックの本体にはクラスの実装が含まれます。 文形式を使用する場合、ファイルの残りの部分は、次の class または package ステートメントまで使い切られます。

class and package declarations are similar, but classes automatically get a constructor named new - You don't have to (and should not) write one. Additionally, in the class BLOCK you are allowed to declare fields and methods.

classpackage の宣言は似ていますが、クラスは自動的に new という 名前のコンストラクタを取得します - あなたはこれを書く必要はありません(書くべきではありません)。 さらに、class の BLOCK の中では、フィールドとメソッドを宣言できます。

field

    field VARIABLE_NAME;

    field VARIABLE_NAME = EXPR;

    field VARIABLE_NAME : ATTRIBUTES;

    field VARIABLE_NAME : ATTRIBUTES = EXPR;

Fields are variables which are visible in the scope of the class - more specifically within "method" and ADJUST blocks. Each class instance get their own storage of fields, independent of each other.

フィールドは、クラスのスコープ内(より具体的には "method" および ADJUST ブロック内)で見える変数です。 各クラス実体は、フィールドのための互いに独立した独自の保管場所を 取得します。

A field behaves like a normal lexically scoped variable. It has a sigil and is private to the class (though creation of an accessor method will make it accessible from the outside). The main difference is that different instances access different values in the same scope.

フィールドは、通常のレキシカルスコープの変数のように振る舞います。 それには印(sigil)があり、クラスに対してプライベートです(ただし、 アクセサメソッドを作成すると、外部からアクセスできるようになります)。 主な違いは、異なる実体は同じスコープ内の異なる値にアクセスすることです。

    class WithFields {
        field $scalar = 42;
        field @array  = qw(this is just an array);
        field %hash   = (species => 'Martian', planet => 'Mars');
    }

Fields may optionally have initializing expressions. If present, the expression will be evaluated within the constructor of each object instance. During each evaluation, the expression can use the value of any previously-set field, as well as see any other variables in scope.

フィールドは、オプションで初期化式を持つことができます。 存在する場合、式は各オブジェクト実体のコンストラクタ内で評価されます。 それぞれの評価中に、式はそれまでに設定されたフィールドの値を使用でき、 スコープ内の他の変数も参照できます。

    class WithACounter {
        my $next_count = 1;
        field $count = $next_count++;
    }

When combined with the :param field attribute, the defaulting expression can use any of the =, //= or ||= operators. Expressions using = will apply whenever the caller did not pass the corresponding parameter to the constructor at all. Expressions using //= will also apply if the caller did pass the parameter but the value was undefined, and expressions using ||= will apply if the value was false.

:param フィールド属性と組み合わせた場合、デフォルト式では、 =, //=, ||$= 演算子のいずれかを使えます。 = を使った式は、呼び出し側がコンストラクタに対応する引数を まったく渡さなかった場合に適用されます。 //= を使った式は、呼び出し側が引数を渡したが値が 未定義であった場合にも適用され、 ||= を使った式は、値が偽であった場合に適用されます。

method

    method METHOD_NAME SIGNATURE BLOCK

    method METHOD_NAME BLOCK

    method SIGNATURE BLOCK

    method BLOCK

Methods are subroutines intended to be called in the context of class objects.

メソッドは、クラスオブジェクトのコンテキスト内で呼び出されることを目的とした サブルーチンです。

A variable named $self populated with the current object instance will automatically be created in the lexical scope of method.

現在のオブジェクト実体が設定された $self という名前の変数が、 method のレキシカルスコープに自動的に作成されます。

Methods always act as if use feature 'signatures' is in effect, but $self will not appear in the arguments list as far as the signature is concerned.

メソッドは常に use feature 'signatures' が有効であるかのように 動作しますが、$self はシグニチャに関する限り引数リストには表示されません。

    class WithMethods {
        field $greetings;

        ADJUST {
            $greetings = "Hello";
        }

        method greet($name = "someone") {
            say "$greetings, $name";
        }
    }

Just like regular subroutines, methods can be anonymous:

通常のサブルーチンと同じように、メソッドは匿名にすることが できます

    class AnonMethodFactory {

        method get_anon_method {
            return method {
                return 'this is an anonymous method';
            };
        }
    }

属性

Specific aspects of the keywords mentioned above are managed using attributes. Attributes all start with a colon, and one or more of them can be appended after the item's name, separated by a space.

上述のキーワードの特定の様相は、属性 を使って管理されます。 属性はすべてコロンで始まり、一つまたは複数の属性をアイテム名の後に スペースで区切って追加できます。

クラス属性

:isa

Classes may inherit from one superclass, by using the :isa class attribute.

クラスは、:isa クラス属性を使用して、一つの スーパークラスから 継承できます。

    class Example::Base { ... }

    class Example::Subclass :isa(Example::Base) { ... }

Inherited methods are visible and may be invoked. Fields are always lexical and therefore not visible by inheritance.

継承されたメソッドはアクセス可能で、呼び出すことができます。 フィールドは常にレキシカルであるため、継承によってアクセス可能にはなりません。

The :isa attribute may request a minimum version of the base class; it is applied similar to use - if the provided version is too low it will fail at compile time.

:isa 属性は、基本クラスの最小バージョンを要求する場合があります; これは、use と同様に適用されます - 提供バージョンが低すぎる場合、コンパイル時に失敗します。

    class Example::Subclass :isa(Example::Base 2.345) { ... }

The :isa attribute will attempt to require the named module if it is not already loaded.

:isa 属性は、指定されたモジュールがまだロードされていない場合、 そのモジュールを require しようとします。

フィールド属性

:param

A scalar field with a :param attribute will take its value from a named parameter passed to the constructor. By default the parameter will have the same name as the field (minus its leading $ sigil), but a different name can be specified in the attribute.

:param 属性を持つスカラーフィールドは、コンストラクタに渡された 名前付き引数から値を取得します。 デフォルトでは、引数はフィールドと同じ名前 (先頭の $ 印を除く) を 持ちますが、属性で別の名前を指定できます。

    field $x :param;
    field $y :param(the_y_value);

If there is no defaulting expression then the parameter is required by the constructor; the caller must pass it or an exception is thrown. With a defaulting expression this becomes optional.

デフォルトの式がない場合、コンストラクタには引数が必要です; 呼び出し元はパラメータを渡す必要があり、渡さない場合は例外が投げられます。 デフォルトの式を使用すると、これはオプションになります。

メソッド属性

None yet.

まだありません。

オブジェクトのライフサイクル

構築

Each object begins its life with a constructor call. The constructor is always named new and is invoked like a method call on the class name:

各オブジェクトは、コンストラクタ呼び出しから始まります。 コンストラクタは常に new という名前で、クラス名に対する メソッド呼び出しのように呼び出されます。

    my $object = My::Class->new(%arguments);

During the construction, class fields are compared to %arguments hash and populated where possible.

構築中に、クラスフィールドは %arguments ハッシュと比較され、 可能な場所では値が設定されます。

調整

Object adjustment can be performed during the construction to run user-defined code. It is done with the help of ADJUST blocks, which are called in order of declaration.

オブジェクトの調整は、ユーザ定義コードを実行するための構築中に実行できます。 これは、宣言の順序で呼び出される ADJUST ブロックの助けを借りて行われます。

They are similar to BEGIN blocks, which run during the compilation of a package. However, they also have access to $self lexical (object instance) and all object fields created up to that point.

これらは、パッケージのコンパイル中に実行される BEGIN ブロックに 似ていますが、$self レキシカル変数(オブジェクト実体)および その時点までに作成されたすべてのオブジェクトフィールドにもアクセスできます。

生存期間

After the construction phase, object is ready to be used.

構築フェーズの後、オブジェクトは使用可能な状態になります。

Using blessed (Scalar::Util::blessed or builtin::blessed) on the object will return the name of the class, while reftype (Scalar::Util::reftype or builtin::reftype) will return the string 'OBJECT'.

オブジェクトに対して blessed (Scalar::Util::blessed または builtin::blessed) を使うと、クラスの名前が返されます; 一方、reftype(Scalar::Util::reftype または builtin::reftype) を 使うと、文字列 'OBJECT' が返されます。

破棄

Just like with other references, when object reference count reaches zero it will automatically be destroyed.

他のリファレンスと同様に、オブジェクト参照カウントがゼロになると、 自動的に破棄されます。

TODO

This feature is still experimental and very incomplete. The following list gives some overview of the kinds of work still to be added or changed:

この機能はまだ実験的であり、非常に不完全です。 次のリストは、追加または変更される作業の種類の概要を示しています。

  • Roles

    (ロール)

    Some syntax for declaring a role (likely a role keyword), and for consuming a role into a class (likely a :does() attribute).

    (role キーワードのような) ロールを宣言するための構文と、 (:does() 属性のような) ロールをクラスに取り込むための構文。

  • Parameters to ADJUST blocks

    (ADJUST ブロックへの引数)

    Some syntax for declaring that an ADJUST block can consume named parameters, which become part of the class constructor's API. This might be inspired by a similar plan to add named arguments to subroutine signatures.

    ADJUST ブロックがクラスコンストラクタの API の一部となる 名前付き引数を消費できることを宣言するためのいくつかの構文。 これは、名前付き引数をサブルーチンシグネチャに追加する 同様の計画に触発された可能性があります。

        class X {
            ADJUST (:$alpha, :$beta = 123) {
               ...
            }
        }
    
        my $obj = X->new(alpha => 456);
  • ADJUST blocks as true blocks

    (真のブロックとしての ADJUST ブロック)

    Currently, every ADJUST block is wrapped in its own CV that gets invoked with the full ENTERSUB overhead. It should be possible to use the same mechanism that makes all field initializer expressions appear within the same CV on ADJUST blocks as well, merging them all into a single CV per class. This will make it faster to invoke if a class has more than one of them.

    現在、すべての ADJUST ブロックは、完全な ENTERSUB オーバーヘッドで 呼び出される独自の CV にラップされています。 すべてのフィールド初期化式を ADJUST ブロックの同じ CV 内に表示する 同じ機構を使って、クラスごとにすべてを 単一の CV にマージすることも可能です。 これにより、クラスに複数の CV がある場合の呼び出しが高速になります。

  • Accessor generator attributes

    (アクセサ生成属性)

    Attributes to request that accessor methods be generated for fields. Likely :reader and :writer.

    フィールドに対してアクセサメソッドの生成を要求する属性。 :reader および :writer が考えられます。

        class X {
            field $name :reader;
        }

    Equivalent to

    次と同等です:

        class X {
            field $name;
            method name { return $name; }
        }
  • Metaprogramming

    (メタプログラミング)

    An extension of the metaprogramming API (currently proposed by RFC0022) which adds knowledge of classes, methods, fields, ADJUST blocks, and other such class-related details.

    (現在 RFC0022 によって 提案されている) メタプログラミング API の拡張で、クラス、メソッド、 フィールド、ADJUST ブロック、およびその他のクラス関連の 詳細に関する知識を追加します。

  • Extension Customisation

    (拡張のカスタマイズ)

    Ways in which out-of-core modules can interact with the class system, including an ability for them to provide new class or field attributes.

    コア外モジュールがクラスシステムと相互作用する方法; これには、新しいクラスまたはフィールド属性を提供する機能が含まれます。

作者

Paul Evans

Bartosz Jarzyna