Search code examples
perlmoose

Moose: attributes check by creating an object


I make my first steps with Moose and I have the following question. It seems that I can assign the attributes which I do not specified in the module. The error message comes if I attempt to access this attribute. How could I prevent the very assignment of the attribute which was not specified in the module? In the example below I assign age though I did not specified this in the module. This is silently accepted unless I try to say it. I would like that error message comes after the ->new statement already.

The code:

 #!/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.

Thank you!


Solution

  • Give this a try:

    use MooseX::StrictConstructor;
    

    Which will throw an error like this when you pass age into the constructor:

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