Perl6Attribute - An example attribute metaclass for Perl 6 style attributes
package Foo; Foo->meta->add_attribute(Perl6Attribute->new('$.foo')); Foo->meta->add_attribute(Perl6Attribute->new('@.bar')); Foo->meta->add_attribute(Perl6Attribute->new('%.baz')); sub new { my $class = shift; $class->meta->new_object(@_); }
This is an attribute metaclass which implements Perl 6 style attributes, including the auto-generating accessors.
This code is very simple, we only need to subclass Class::MOP::Attribute and override &new. Then we just pre-process the attribute name, and create the accessor name and default value based on it.
Class::MOP::Attribute
&new
More advanced features like the handles trait (see "A12" in Perl6::Bible) can be accomplished as well doing the same pre-processing approach. This is left as an exercise to the reader though (if you do it, please send me a patch though, and will update this).
handles
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 Class::MOP, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::MOP
CPAN shell
perl -MCPAN -e shell install Class::MOP
For more information on module installation, please visit the detailed CPAN module installation guide.