我和Moose迈出了第一步,我有以下问题.似乎我可以分配我未在模块中指定的属性.如果我尝试访问此属性,则会出现错误消息.我怎么能阻止模块中未指定的属性的赋值?在下面的例子中,我指定了年龄,虽然我没有在模块中指定它.除非我试着说,否则这是默默接受的.我想在 - >新语句之后出现错误消息.
代码:
#!/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.
Run Code Online (Sandbox Code Playgroud)
谢谢!
尝试一下:
use MooseX::StrictConstructor;
Run Code Online (Sandbox Code Playgroud)
当你将age传递给构造函数时,会抛出这样的错误:
Found unknown attribute(s) passed to the constructor: age ...
Run Code Online (Sandbox Code Playgroud)