在現代 Perl 中定義類

儘管可用,但在現代 Perl 中不建議從頭開始定義類。使用輔助 OO 系統之一,提供更多功能和便利。這些系統包括:

駝鹿

package Foo;
use Moose;

has bar => (is => 'ro');                 # a read-only property
has baz => (is => 'rw', isa => 'Bool');  # a read-write boolean property

sub qux {
    my $self = shift;
    my $barIsBaz = $self->bar eq 'baz';  # property getter
    $self->baz($barIsBaz);               # property setter
}

Class::Accessor(Moose 語法)

package Foo;
use Class::Accessor 'antlers';

has bar => (is => 'ro');                 # a read-only property
has baz => (is => 'rw', isa => 'Bool');  # a read-write property (only 'is' supported, the type is ignored)

Class::Accessor(本機語法)

package Foo;
use base qw(Class::Accessor);

Foo->mk_accessors(qw(bar baz));  # some read-write properties
Foo->mk_accessors(qw(qux));      # a read-only property

類::微小

package Foo;
use Class::Tiny qw(bar baz);  # just props