【问题标题】:Moose: attributes check by creating an objectMoose:通过创建对象进行属性检查
【发布时间】:2013-02-17 13:45:16
【问题描述】:

我与 Moose 一起迈出了第一步,我有以下问题。 似乎我可以分配模块中未指定的属性。如果我尝试访问此属性,则会出现错误消息。如何防止模块中未指定的属性的分配?在下面的示例中,我指定了年龄,尽管我没有在模块中指定。除非我试图说出来,否则这是默默接受的。我希望该错误消息已经出现在 ->new 语句之后。

代码:

 #!/usr/bin/perl
 use strict;
 use warnings;

 use 5.012;
 package People;
 use Moose;
 use namespace::autoclean;
 has 'name' => (is => 'rw');
 __PACKAGE__->meta->make_immutable;

 package main;
 my $friend = People->new( name => 'Peter', age => 20 ); # no error.
 say $friend->name;
 say $friend->age; # here comes the error message.

谢谢!

【问题讨论】:

    标签: perl moose


    【解决方案1】:

    试试这个:

    use MooseX::StrictConstructor;
    

    当你将年龄传递给构造函数时会抛出这样的错误:

    Found unknown attribute(s) passed to the constructor: age ...
    

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多