Movatterモバイル変換


[0]ホーム

URL:


perlclass
(source,CPAN)

CONTENTS

#NAME

perlclass - Perl class syntax reference

#SYNOPSIS

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;

#DESCRIPTION

This document describes the syntax of Perl'sclass feature, which provides native keywords for object-oriented programming.

#History

Since Perl 5, support for objects revolved around the concept ofblessing references with a package name (see"bless REF,CLASSNAME" in perlfunc). Such a 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. For more information, seeperlmod andperlobj.

Theclass feature is a core implementation of a class syntax that is similar to what one would find in other programming languages. It is not a wrapper aroundbless, but a completely new system built right into the perl interpreter.

#KEYWORDS

Enabling theclass feature allows the usage of the following new keywords in the current lexical scope:

#class

class NAME BLOCKclass NAME VERSION BLOCKclass NAME VERSION : ATTRIBUTES... BLOCKclass NAME;class NAME VERSION;class NAME VERSION : ATTRIBUTES...;

Theclass keyword declares a new package (see"Packages" in perlmod) that is intended to be a class. All other keywords from theclass feature should be used within the scope of this declaration.

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 current scope or file is used up until the nextclass orpackage statement.

Aclass declaration can optionally have a version number, similar to thepackage keyword. It can also optionally have attributes. If both are specified, the version number must come first, before the attributes.

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

#field

field VARIABLE_NAME;field VARIABLE_NAME = EXPR;field VARIABLE_NAME : ATTRIBUTES;field VARIABLE_NAME : ATTRIBUTES = EXPR;

Fields are variables that are visible in the scope of the class - more specifically within"method" andADJUST blocks. Each class instance gets its own storage of fields, independent of other instances.

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.

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

During a field initializing expression, the instance is not yet constructed and so the$self lexical is not available. However, the special__CLASS__ token may be used to obtain the name of the class being constructed, for example in order to invoke class methods on it to help in constructing values for fields.

class WithCustomField {    use constant DEFAULT_X => 10;    field $x = __CLASS__->DEFAULT_X;}

This allows subclasses to override the method with different behaviour.

class DifferentCustomField :isa(WithCustomField) {    sub DEFAULT_X { rand > 0.5 ? 20 : 30 }}

When an instance ofDifferentCustomField is constructed, the__CLASS__ expression in the base will yield the correct class name, and so invoke this overridden method instead.

#method

method METHOD_NAME SIGNATURE BLOCKmethod METHOD_NAME BLOCKmethod SIGNATURE BLOCKmethod 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 ofmethod.

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

class WithMethods {    field $greetings;    ADJUST {        $greetings = "Hello";    }    method greet($name = "someone") {        say "$greetings, $name";    }}

Just like regular subroutines, methodscan be anonymous:

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

Methods can also be declared as lexical subroutines, using themy prefix. This creates a subroutine that is lexically visible within the current scope, but does not appear in the symbol table. The effect is that of aprivate method; one that can be called from within the class's own code, but not from outside.

To invoke these lexical subroutines as methods, it is best to use the->& operator. This bypasses method lookup by name, and directly invokes a lexical subroutine as if it was a method.

class LexicalMethod {    my method abc ($x, $y) {        say "Internal method abc invoked with x=$x y=$y";    }    method xyz {        $self->&abc("x", "y");    }}# The `abc` method is not visible from here

#ATTRIBUTES

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

#Class attributes

#:isa

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

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. As withuse MODULE VERSION, if the actual version of the base class is too low, compilation will fail.

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

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

#Field attributes

#: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.

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.

#:reader

A field with a:reader attribute will generate a reader accessor method automatically. The generated method will have an empty (i.e. zero-argument) signature, and its body will simply return the value of the field variable.

field $s :reader;# Equivalent tofield $s;method s () { return $s; }

By default the accessor method will have the same name as the field (minus the leading sigil), but a different name can be specified in the attribute's value.

field $x :reader(get_x);# Generates a methodmethod get_x () { return $x; }

Reader methods can be applied to non-scalar fields. When invoked in list context, they yield the contents of the field; in scalar context they yield the count of elements, as if the field variable had been placed in scalar context.

field @users :reader;...scalar $instance->users;

#:writer

A field with a:writer attribute will generate a writer accessor method automatically. The generated method will have a signature that consumes exactly one argument, and its body will assign that scalar argument to the field and return the invocant object itself.

field $s :writer;# Equivalent tofield $s;method set_s($new) { $s = $new; return $self; }

By default the accessor method will have the name of the field minus the leading sigil with the stringset_ prefixed to it, but a different name can be specified in the attribute's value.

field $x :writer(write_x);# Generates a methodmethod write_x ($new) { ... }

Currently, writer accessors can only be applied to scalar fields. Attempts to apply this attribute to a non-scalar field will result in a fatal exception at compile-time. This may be relaxed in a future version to allow writers on array or hash fields. For now, these will have to be created manually.

#Method attributes

None yet.

#OBJECT LIFECYCLE

#Construction

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

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

During object construction, class fields are looked up in the%arguments hash and populated where possible.

#Adjustment

Object adjustment is a way to run arbitrary user-defined code during object construction. This is done by placing code inADJUST blocks. Every time an object is constructed, itsADJUST blocks are executed (in the order in which they are declared).

class WellAdjusted {    field $x :param;    ADJUST {        say "Hello!";    }    ADJUST {        say "x = $x";    }}my $object = WellAdjusted->new(x => 42);# Output:#   Hello!#   x = 42

ADJUST blocks are syntactically similar toBEGIN orINIT blocks, which only run once. However,ADJUST blocks, like methods, have access to$self (a lexical variable holding the object being constructed) as well as all object fields created up to that point.

#Lifetime

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

Usingblessed (Scalar::Util::blessed orbuiltin::blessed) on the object will return the name of the class, whilereftype (Scalar::Util::reftype orbuiltin::reftype) will return the string'OBJECT'.

#Destruction

An object is destroyed when the last reference to it goes away, just as with other data structures in Perl.

#TODO

This feature is still experimental and very incomplete. The following list gives an overview of features still to be added or changed:

#KNOWN BUGS

The following bugs have been found in the experimentalclass feature:

#AUTHORS

Paul Evans

Bartosz Jarzyna

Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.


[8]ページ先頭

©2009-2025 Movatter.jp