-2

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

1 回答 1

2

问题是在newCat.pm 的第 64 行定义的。 Moose提供了一个new方法,所以你不需要自己写。删除该new方法,它工作正常。

另一个应该触发“啊哈!” 是个

use 5.006;
use strict;
use warnings;

它位于 Cat.pm 代码的中途。

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

于 2011-06-22T07:41:06.473 回答