Class-Plain
view release on metacpan or search on metacpan
lib/Class/Plain/Document/Cookbook.pm view on Meta::CPAN
my $object = Foo->new(x => 1);
print $object->x . " " . $object->to_string;
=head2 Class::Accessor::Fast
Use L<Class::Accessor::Fast> with L<Class::Plain>.
use Class::Plain;
class Foo {
field x;
use base 'Class::Accessor::Fast';
__PACKAGE__->mk_accessors('x');
method to_string { "String:" . $self->x }
}
my $object = Foo->new(x => 1);
print $object->x . " " . $object->to_string;
=head2 Class::Accessor
Use L<Class::Accessor> with L<Class::Plain>.
use Class::Plain;
class Foo {
field x;
use base 'Class::Accessor::Fast';
__PACKAGE__->mk_accessors('x');
method to_string { "String:" . $self->x }
}
my $object = Foo->new(x => 1);
print $object->x . " " . $object->to_string;
=head2 Mojo::Base
Use L<Mojo::Base> with L<Class::Plain>.
use Class::Plain;
class Foo : isa() {
field x;
use Mojo::Base -base;
has "x";
method to_string { "String:" . $self->x }
}
my $object = Foo->new(x => 1);
print $object->x . " " . $object->to_string;
=head1 Weakening Field
Weaken a field.
use Scalar::Util 'weaken';
use Class::Plain;
class Foo {
field x;
method weaken_x {
weaken $self->{x};
}
}
=head1 Class Variable
A class variable is represented using a package variable or a lexical variable.
use Class::Plain;
class ClassVariable {
# Public
our $FOO;
# Private
my $BAR;
BEGIN {
$FOO = 1;
$BAR = 2;
}
method FOO : common { $FOO }
method BAR : common { $BAR }
}
ClassVariable->FOO: # 1
ClassVariable->BAR; # 2
=head1 Signatures
Use L<Class::Plain> with L<subroutine signatures|https://perldoc.perl.org/perlsub#Signatures> from C<Perl 5.26+>.
use v5.36; # Enable signatures and other features.
use Class::Plain;
class Point {
field x;
field y;
method new : common {
my $self = $class->SUPER::new(@_);
$self->{x} //= 0;
$self->{y} //= 0;
return $self;
}
# Subroutine signatures
method move ($x = 0, $y = 0) {
$self->{x} += $x;
$self->{y} += $y;
}
method describe {
print "A point at ($self->{x}, $self->{y})\n";
}
}
( run in 1.392 second using v1.01-cache-2.11-cpan-39bf76dae61 )