Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Perl OO with Class::Struct

by tobyink (Abbot)
on Dec 13, 2013 at 16:21 UTC ( #1067037=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Perl OO with Class::Struct
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1067037]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2014-08-21 08:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (128 votes), past polls