PerlMoose属性不强制进行类型检查



我正在使用草莓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

问题是在Cat.pm的第64行定义的newMoose提供了new方法,因此您不需要编写自己的方法。删除new方法,它就可以正常工作。

另一个应该触发"啊哈!"的是

use 5.006;
use strict;
use warnings;

它位于您的Cat.pm代码的一半。

如果您要使用POD文档,您应该将代码嵌入文档中(允许文档增强内联注释);或者,您应该将所有代码放在顶部,并在底部制作一个清晰的POD。无论哪种方式,一致性都将有助于避免未来出现此类问题。

相关内容

  • 没有找到相关文章

最新更新