我使用草莓 perl,Moose 2.0010
在课堂里:
package Cat;
use 5.010;
use strict;
use Moose;
has 'name', is => 'ro', isa => 'Str', default => 'Beauty';
#has 'age', is => 'ro';
has 'diet', is => 'rw', default => 'fish';
has 'birth_year', is => 'ro', isa=> 'Int',
default => 1997;
在应用中:
use 5.010;
use strict;
use Cat;
my $kitty = Cat->new(name => 123, diet => 'Sea food',
birth_year => 'nineteen ninety seven');
say 'I have a kitten named ', $kitty->name(), ' eats ', $kitty->diet(),
' birth at ', $kitty->birth_year();
输出:
I have a kitten named 123 eats Sea food birth at nineteen ninety seven
Press any key to continue . . .
它不强制类型检查。
编辑:完整代码,其余代码由 Padre 生成,我没有删除。Padre 添加尾随 1;:
package Cat;
use 5.010;
use strict;
use Moose;
has 'name', is => 'ro', isa => 'Str', default => 'Beauty';
#has 'age', is => 'ro';
has 'diet', is => 'rw', default => 'fish';
has 'birth_year', is => 'ro', isa=> 'Int',
default => 1997;
sub age
{
my $self = shift;
my $year = (localtime)[5] + 1900;
return $year - $self->birth_year();
}
=pod
=head1 NAME
Cat - My author was too lazy to write an abstract
=head1 SYNOPSIS
my $object = Cat->new(
foo => 'bar',
flag => 1,
);
$object->dummy;
=head1 DESCRIPTION
The author was too lazy to write a description.
=head1 METHODS
=cut
use 5.006;
use strict;
use warnings;
our $VERSION = '0.01';
=pod
=head2 new
my $object = Cat->new(
foo => 'bar',
);
The C<new> constructor lets you create a new B<Cat> object.
So no big surprises there...
Returns a new B<Cat> or dies on error.
=cut
sub new {
my $class = shift;
my $self = bless { @_ }, $class;
return $self;
}
=pod
=head2 dummy
This method does something... apparently.
=cut
sub dummy {
my $self = shift;
# Do something here
return 1;
}
1;
=pod
=head1 SUPPORT
No support is available
=head1 AUTHOR
Copyright 2011 Anonymous.
=cut