2013-02-17 78 views
3

我使用Moose開始了我的第一步,並且我有以下問題。 看來我可以分配我沒有在模塊中指定的屬性。如果我嘗試訪問此屬性,則會顯示錯誤消息。我怎樣才能防止在模塊中未指定的屬性的分配?在下面的例子中,我指定了年齡,雖然我沒有在模塊中指定它。這是默默接受,除非我試圖說出來。我希望那個錯誤信息出現在 - > new語句之後。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. 

謝謝!

回答

5

試試這個:

use MooseX::StrictConstructor; 

當你通過年齡到構造函數會拋出這樣的錯誤:

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

謝謝你的工作! – 2013-02-17 17:15:06