问题
I an using strawberry perl, Moose 2.0010
In the class:
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;
In application:
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();
The output:
I have a kitten named 123 eats Sea food birth at nineteen ninety seven
Press any key to continue . . .
It doesn't force type checking.
Edit: The complete code, the rest of code is generated by Padre, I haven't delete it. Padre added trailing 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
回答1:
The problem is the new
defined at line 64 of Cat.pm. Moose
provides a new
method, so you don't need to write your own. Remove that new
method, and it works fine.
The other bit that should have triggered a "aha!" is the
use 5.006;
use strict;
use warnings;
which is present halfway down your Cat.pm code.
If you're going to use POD documentation, you should either embed your code within the docs (allowing the docs to enhance your inline comments); or you should put all your code up top and make a clear POD at the bottom. Either way, consistency will help avoid these kinds of problems in the future.
来源:https://stackoverflow.com/questions/6434597/perl-moose-attribute-not-force-type-checking