http://www.perlmonks.org?node_id=1067037


in reply to Perl OO with Class::Struct

Yes, if you need proper validation, you've outgrown Class::Struct. Here are a few options...

Moose

use strict; use warnings; { package Cat; use Moose; has name => ( is => 'ro', isa => 'Str', ); __PACKAGE__->meta->make_immutable; } { package Litter; use Moose; has cats => ( is => 'ro', isa => 'ArrayRef[Cat]', ); __PACKAGE__->meta->make_immutable; } my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2, 1]);

Mouse

(Same as Moose; just use Mouse instead of use Moose.)

Moo

use strict; use warnings; { package Cat; use Moo; use Types::Standard -types; has name => ( is => 'ro', isa => Str, ); } { package Litter; use Moo; use Types::Standard -types; has cats => ( is => 'ro', isa => ArrayRef[InstanceOf['Cat']], ); } my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2, 1]);

Moops

use Moops; class Cat :ro { has name => (isa => Str); } class Litter :ro { has cats => (isa => ArrayRef[InstanceOf['Cat']]); } my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2, 1]);

MooX::Struct

use strict; use warnings; use Types::Standard -types; use MooX::Struct Cat => ['$name']; use MooX::Struct Litter => ['@cats' => [ isa => ArrayRef[InstanceOf[Ca +t]] ]]; my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2, 1]);

MooseX::Struct

The release of Moose 2.02 broke MooseX::Struct, and nobody's been bothered enough to fix it. :-( However, this is how it should work according to the documentation:

use strict; use warnings; use MooseX::Struct; immutable struct Cat => ( name => { isa => 'Str' }, ); immutable struct Litter => ( cats => { isa => 'ArrayRef[Cat]' }, ); my $cat1 = Cat->new(name=>'Garfield'); my $cat2 = Cat->new(name=>'Felix'); my $litter = Litter->new(cats => [$cat1, $cat2, 1]);
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name