skirnir has asked for the wisdom of the Perl Monks concerning the following question:

Hi, today I've been dabbling with Moose for the first time. After reading the doc for Moose::Util::TypeConstraints, I would have expected this example to result in $stuff to be instantiated with [ 1, 2 ] in 'somearray':

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; package MyClass; use Moose; #use Moose::Util::TypeConstraints; has 'somearray' => ( is => 'rw', isa => 'ArrayRef[Int]'); #has 'somearray' => ( is => 'rw', isa => 'ArrayRef'); 1; package main; #use Moose; #use Moose::Util::TypeConstraints; my @array = (1,2); print Dumper(@array); my $stuff = new MyClass(somearray => \@array); print Dumper($stuff);

Instead I get the following error message:

Attribute (somearray) does not pass the type constraint (__ANON__) wit +h 'ARRAY(0x81d3b74)' at /usr/share/perl5/Moose/Meta/Attribute.pm line + 221 Moose::Meta::Attribute::initialize_instance_slot('Moose::Meta: +:Attribute=HASH(0x8451b3c)', 'Moose::Meta::Instance=HASH(0x8451f5c)', + 'MyClass=HASH(0x84520dc)', 'HASH(0x835c518)') called at /usr/share/p +erl5/Moose/Meta/Class.pm line 102 Moose::Meta::Class::construct_instance('Moose::Meta::Class=HAS +H(0x844b9a4)', 'somearray', 'ARRAY(0x81d3b74)') called at /usr/share/ +perl5/Class/MOP/Class.pm line 306 Class::MOP::Class::new_object('Moose::Meta::Class=HASH(0x844b9 +a4)', 'somearray', 'ARRAY(0x81d3b74)') called at /usr/share/perl5/Moo +se/Meta/Class.pm line 81 Moose::Meta::Class::new_object('Moose::Meta::Class=HASH(0x844b +9a4)', 'somearray', 'ARRAY(0x81d3b74)') called at /usr/share/perl5/Mo +ose/Object.pm line 26 Moose::Object::new('MyClass', 'somearray', 'ARRAY(0x81d3b74)') + called at moose_test.pl line 26

When commenting out the has 'somearray'.... line and replacing it with the one commented out above,I get the $stuff object I expect.
Can anyone tell me what I am doing wrong here?

Replies are listed 'Best First'.
Re: Type Constraints in Moose
by FunkyMonk (Bishop) on Apr 06, 2008 at 16:33 UTC
    It works exactly as posted for me (well, I did add a backslash to the first call to Dumper). I'm using Moose 0.40 here, what version are you using?
    $VAR1 = [ 1, 2 ]; $VAR1 = bless( { 'somearray' => [ 1, 2 ] }, 'MyClass' );

      I was using the libmoose-perl package of ubuntu 7.10. It turned out to be Moose 0.21.
      I wouldn't have thought that they were that far behind, so I didn't check versions before.
      Sorry, my fault. It works like a charm now with 0.40. Thanks for your help!
        For future reference, (and hoping Ubuntu works the same as Debian):

        When a CPAN module is out of date on Debian, or not available, I use dh-make-perl <module-name> to create my own package and install it with dpkg or apt-get. Mostly it works great, and has the advantage that if the Debian maintainer updates their package, apt-get (or whatever) will do the right thing.