LazyClass - An example metaclass with lazy initialization
package BinaryTree; use metaclass ( ':attribute_metaclass' => 'LazyClass::Attribute', ':instance_metaclass' => 'LazyClass::Instance', ); BinaryTree->meta->add_attribute('node' => ( accessor => 'node', init_arg => ':node' )); BinaryTree->meta->add_attribute('left' => ( reader => 'left', default => sub { BinaryTree->new() } )); BinaryTree->meta->add_attribute('right' => ( reader => 'right', default => sub { BinaryTree->new() } )); sub new { my $class = shift; $class->meta->new_object(@_); } # ... later in code my $btree = BinaryTree->new(); # ... $btree is an empty hash, no keys are initialized yet
This is an example metclass in which all attributes are created lazily. This means that no entries are made in the instance HASH until the last possible moment.
The example above of a binary tree is a good use for such a metaclass because it allows the class to be space efficient without complicating the programing of it. This would also be ideal for a class which has a large amount of attributes, several of which are optional.
Stevan Little <stevan@iinteractive.com>
Yuval Kogman <nothingmuch@woobling.com>
Copyright 2006-2008 by Infinity Interactive, Inc.
http://www.iinteractive.com
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Moose, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Moose
CPAN shell
perl -MCPAN -e shell install Moose
For more information on module installation, please visit the detailed CPAN module installation guide.