-
-
07 Nov 2021 03:41:58 UTC
- Distribution: Moose
- Source (raw)
- Browse (raw)
- Changes
- Homepage
- How to Contribute
- Repository
- Issues (71)
- Testers (2647 / 3 / 1)
- Kwalitee
Bus factor: 3- 92.11% Coverage
- License: perl_5
- Perl: v5.8.3
- Activity
24 month- Tools
- Download (881.54KB)
- MetaCPAN Explorer
- Permissions
- Subscribe to distribution
- Permalinks
- This version
- Latest version
and 142 contributors-
Stevan Little
-
Dave Rolsky
-
Jesse Luehrs
-
Shawn M Moore
-
יובל קוג'מן (Yuval Kogman)
-
Florian Ragwitz
-
Hans Dieter Pearcey
-
Chris Prather
-
Matt S Trout
-
Upasana Shukla
-
Graham Knop
-
Tomas Doran
-
Ricardo Signes
-
Guillermo Roditi
-
John Napiorkowski
-
Aankhen
-
Todd Hepler
-
Jonathan Rockway
-
Gerda Shank
-
Perlover
-
Shlomi Fish
-
Brad Bowman
-
Justin Hunter
-
Kent Fredric
-
Paul Driver
-
Anders Nor Berle
-
Brian Manning
-
gfx
-
Jay Hannah
-
Lars Dɪᴇᴄᴋᴏᴡ 迪拉斯
-
Leon Brocard
-
Olivier Mengué
-
Rafael Kitover
-
Christian Hansen
-
Cory Watson
-
Dagfinn Ilmari Mannsåker
-
Paul Jamieson Fenwick
-
Robert Buels
-
Dan Dascalescu
-
Marcel Grünauer
-
Scott McWhirter
-
Ævar Arnfjörð Bjarmason
-
Daisuke Maki (lestrrat)
-
Dylan William Hardison
-
Patrick Donelan
-
Stefan O'Rear
-
Tokuhiro Matsuno
-
Ash Berlin
-
Chris Weyl
-
Eric Wilhelm
-
Jess Robinson
-
Marc Mims
-
Marcus Ramberg
-
Mark Allen
-
Mateu X Hunter
-
matthof
-
Robert 'phaylon' Sedlacek
-
Zachary Lome
-
Aran Clary Deltac
-
Chip
-
Christopher J. Madsen
-
Curtis Jewell
-
Evan Carroll
-
Mark A. Stratman
-
Mark Fowler
-
Matthew Horsfall
-
mauke
-
Michael LaGrasta
-
Michael Rykov
-
Mike Whitaker
-
Moritz Onken
-
Nelo Onyiah
-
Nick Perez
-
Robert Boone
-
Robin V
-
rodrigolive
-
shelling
-
Thomas Sibley
-
Tom Hukins
-
Wallace Reis
-
Aaron Cohen
-
Adam J. Foxson
-
Adam Kennedy
-
Andy Jack
-
Anirvan Chatterjee
-
Ansgar Burchardt
-
A. Sinan Unur
-
Ben Hutton
-
Brendan Byrd
-
Chad Granum
-
Chankey Pathak
-
Chia-liang Kao
-
Christian Walde (Mithaldu)
-
chromatic
-
Dann
-
Dave Romano
-
David Leadbeater
-
David Steinbrunner
-
dmaestro
-
E. Choroba
-
franck cuny
-
Frew Schmidt
-
gregor herrmann
-
hakim
-
Henry Van Styn
-
James Marca
-
Jason May
-
Jay Allen
-
Jay Kuri
-
Jeff Bisbee
-
Jens Berthold
-
Jesse Vincent
-
joel
-
John Douglas Porter
-
John Goulah
-
Justin DeVuyst
-
Kang-min Liu
-
Leon Timmermans
-
Mark O Grady
-
Matt Kraai
-
Michael Schout
-
Nathan Gray
-
Olaf Alders
-
Olof Johansson
-
Paul Cochrane
-
Paweł Murias
-
Pedro Melo
-
Peter Shangov
-
Philippe Bruhat (BooK)
-
Philipp Gortan
-
Phillip Smith
-
Piotr Roszatycki
-
pktm
-
rouzier
-
Sam Vilain
-
sherrardb
-
Simon Reinhardt
-
sue spence
-
Tuomas Jormola
-
wickline
-
Yanick Champoux
-
Zoffix Znet
- Dependencies
- Carp
- Class::Load
- Class::Load::XS
- Data::OptList
- Devel::GlobalDestruction
- Devel::OverloadInfo
- Devel::StackTrace
- Dist::CheckConflicts
- Eval::Closure
- List::Util
- MRO::Compat
- Module::Runtime
- Module::Runtime::Conflicts
- Package::DeprecationManager
- Package::Stash
- Package::Stash::XS
- Params::Util
- Scalar::Util
- Sub::Exporter
- Sub::Util
- Try::Tiny
- parent
- strict
- warnings
- Reverse dependencies
- CPAN Testers List
- Dependency graph
NAME
Moose::Cookbook::Basics::BinaryTree_AttributeFeatures - Demonstrates various attribute features including lazy, predicates, weak refs, and more
VERSION
version 2.2201
SYNOPSIS
package BinaryTree; use Moose; has 'node' => ( is => 'rw', isa => 'Any' ); has 'parent' => ( is => 'rw', isa => 'BinaryTree', predicate => 'has_parent', weak_ref => 1, ); has 'left' => ( is => 'rw', isa => 'BinaryTree', predicate => 'has_left', lazy => 1, default => sub { BinaryTree->new( parent => $_[0] ) }, trigger => \&_set_parent_for_child ); has 'right' => ( is => 'rw', isa => 'BinaryTree', predicate => 'has_right', lazy => 1, default => sub { BinaryTree->new( parent => $_[0] ) }, trigger => \&_set_parent_for_child ); sub _set_parent_for_child { my ( $self, $child ) = @_; confess "You cannot insert a tree which already has a parent" if $child->has_parent; $child->parent($self); }
DESCRIPTION
This recipe shows how various advanced attribute features can be used to create complex and powerful behaviors. In particular, we introduce a number of new attribute options, including
predicate
,lazy
, andtrigger
.The example class is a classic binary tree. Each node in the tree is itself an instance of
BinaryTree
. It has anode
, which holds some arbitrary value. It hasright
andleft
attributes, which refer to its child trees, and aparent
.Let's take a look at the
node
attribute:has 'node' => ( is => 'rw', isa => 'Any' );
Moose generates a read-write accessor for this attribute. The type constraint is
Any
, which literally means it can contain anything.We could have left out the
isa
option, but in this case, we are including it for the benefit of other programmers, not the computer.Next, let's move on to the
parent
attribute:has 'parent' => ( is => 'rw', isa => 'BinaryTree', predicate => 'has_parent', weak_ref => 1, );
Again, we have a read-write accessor. This time, the
isa
option says that this attribute must always be an instance ofBinaryTree
. In the second recipe, we saw that every time we create a Moose-based class, we also get a corresponding class type constraint.The
predicate
option is new. It creates a method which can be used to check whether or not a given attribute has been initialized. In this case, the method is namedhas_parent
.This brings us to our last attribute option,
weak_ref
. Sinceparent
is a circular reference (the tree inparent
should already have a reference to this one, in itsleft
orright
attribute), we want to make sure that we weaken the reference to avoid memory leaks. Ifweak_ref
is true, it alters the accessor function so that the reference is weakened when it is set.Finally, we have the
left
andright
attributes. They are essentially identical except for their names, so we'll just look atleft
:has 'left' => ( is => 'rw', isa => 'BinaryTree', predicate => 'has_left', lazy => 1, default => sub { BinaryTree->new( parent => $_[0] ) }, trigger => \&_set_parent_for_child );
There are three new options here,
lazy
,default
, andtrigger
. Thelazy
anddefault
options are linked. In fact, you cannot have alazy
attribute unless it has adefault
(or abuilder
, but we'll cover that later). If you try to make an attribute lazy without a default, class creation will fail with an exception. (2)In the second recipe the BankAccount's
balance
attribute had a default value of0
. Given a non-reference, Perl copies the value. However, given a reference, it does not do a deep clone, instead simply copying the reference. If you just specified a simple reference for a default, Perl would create it once and it would be shared by all objects with that attribute.As a workaround, we use an anonymous subroutine to generate a new reference every time the default is called.
has 'foo' => ( is => 'rw', default => sub { [] } );
In fact, using a non-subroutine reference as a default is illegal in Moose.
# will fail has 'foo' => ( is => 'rw', default => [] );
This will blow up, so don't do it.
You'll notice that we use
$_[0]
in our default sub. When the default subroutine is executed, it is called as a method on the object.In our case, we're making a new
BinaryTree
object in our default, with the current tree as the parent.Normally, when an object is instantiated, any defaults are evaluated immediately. With our
BinaryTree
class, this would be a big problem! We'd create the first object, which would immediately try to populate itsleft
andright
attributes, which would create a newBinaryTree
, which would populate itsleft
andright
slots. Kaboom!By making our
left
andright
attributeslazy
, we avoid this problem. If the attribute has a value when it is read, the default is never executed at all.We still have one last bit of behavior to add. The autogenerated
right
andleft
accessors are not quite correct. When one of these is set, we want to make sure that we update the parent of theleft
orright
attribute's tree.We could write our own accessors, but then why use Moose at all? Instead, we use a
trigger
. Atrigger
accepts a subroutine reference, which will be called as a method whenever the attribute is set. This can happen both during object construction or later by passing a new object to the attribute's accessor method. However, it is not called when a value is provided by adefault
orbuilder
.sub _set_parent_for_child { my ( $self, $child ) = @_; confess "You cannot insert a tree which already has a parent" if $child->has_parent; $child->parent($self); }
This trigger does two things. First, it ensures that the new child node does not already have a parent. This is done for the sake of simplifying the example. If we wanted to be more clever, we would remove the child from its old parent tree and add it to the new one.
If the child has no parent, we will add it to the current tree, and we ensure that is has the correct value for its
parent
attribute.As with all the other recipes, BinaryTree can be used just like any other Perl 5 class. A more detailed example of its usage can be found in t/recipes/basics_binarytree_attributefeatures.t.
CONCLUSION
This recipe introduced several of Moose's advanced features. We hope that this inspires you to think of other ways these features can be used to simplify your code.
FOOTNOTES
- (1)
-
Weak references are tricky things, and should be used sparingly and appropriately (such as in the case of circular refs). If you are not careful, attribute values could disappear "mysteriously" because Perl's reference counting garbage collector has gone and removed the item you are weak-referencing.
In short, don't use them unless you know what you are doing :)
- (2)
-
You can use the
default
option without thelazy
option if you like, as we showed in the second recipe.Also, you can use
builder
instead ofdefault
. See Moose::Cookbook::Basics::BinaryTree_BuilderAndLazyBuild for details.
AUTHORS
Stevan Little <stevan@cpan.org>
Dave Rolsky <autarch@urth.org>
Jesse Luehrs <doy@cpan.org>
Shawn M Moore <sartak@cpan.org>
יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
Karen Etheridge <ether@cpan.org>
Florian Ragwitz <rafl@debian.org>
Hans Dieter Pearcey <hdp@cpan.org>
Chris Prather <chris@prather.org>
Matt S Trout <mstrout@cpan.org>
COPYRIGHT AND LICENSE
This software is copyright (c) 2006 by Infinity Interactive, Inc.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
Module Install Instructions
To install Moose, copy and paste the appropriate command in to your terminal.
cpanm Moose
perl -MCPAN -e shell install Moose
For more information on module installation, please visit the detailed CPAN module installation guide.