After the nth person telling me to try Moose, I finally gave in.

The first thing I wanted to know was how to handle private variables, hash table properties, and object type properties. The Moose Quick-Ref Card lists the built-in Data Type constraints. I think Randal L. Schwartz has written the definitive introduction, though. (His follow up goes into more detail about custom types….)

We can see below that the read-only field on the Example object needed to have a writer defined for it. Even though the method is named private_set_x, it can still be called from the outside world. Also, we can set the “read only” member via the constructor hash! Hash and object property types seem to work just fine. The only real trick there was to use an in-line sub to initialize them.

#!/usr/bin/perl package Example; use Moose; has 'x' => (isa => 'Int', is => 'ro', writer => 'private_set_x', default => 21); sub test { my $self = shift; my $x = $self->x(); print "My x is currently a $x

"; } sub setit { my $self = shift; $self->private_set_x(42); } package Another; use Moose; extends 'Example'; has 'hashtest' => (isa => 'HashRef', is => 'rw', default => sub { my %hash; return \%hash; } ); has 'exampletest' => (isa => 'Example', is => 'rw', default => sub { Example->new(); } ); after 'setit' => sub { my $self = shift; print "The after method is getting called now.

"; }; my $thing = Example->new(); $thing->test(); #My x is currently a 21 $thing->setit(); $thing->test(); #My x is currently a 42 $thing->private_set_x(84); $thing->test(); #My x is currently a 84 my $otherthing = Example->new(x => 168); $otherthing->test(); # My x is currently a 168 my $another = Another->new(); $another->setit(); # The after method is getting called now. my $h = $another->hashtest(); $h->{"One"} = "Hello"; my $v = $another->hashtest()->{"One"}; print "The hash value is $v

"; # The hash value is Hello my $e = $another->exampletest(); $e->test(); # My x is currently a 21

Share this: Twitter

Facebook

Like this: Like Loading... Related