Perl Moose属性不强制类型检查

时间:2011-06-22 03:30:16

标签: perl moose padre

我使用草莓perl, 穆斯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

1 个答案:

答案 0 :(得分:2)

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

应该触发“aha!”的另一位是

use 5.006;
use strict;
use warnings;

位于Cat.pm代码的中间位置。

如果您要使用POD文档,则应将代码嵌入到文档中(允许文档增强内联注释);或者你应该把你所有的代码放在最上面,并在底部做一个明确的POD。无论哪种方式,一致性将有助于避免将来出现这类问题。