2 package # hide the package from PAUSE
10 use base 'Class::MOP::Attribute';
13 my ($class, $attribute_name, %options) = @_;
15 # extract the sigil and accessor name
16 my ($sigil, $accessor_name) = ($attribute_name =~ /^([\$\@\%])\.(.*)$/);
18 # pass the accessor name
19 $options{accessor} = $accessor_name;
21 # create a default value based on the sigil
22 $options{default} = sub { [] } if ($sigil eq '@');
23 $options{default} = sub { {} } if ($sigil eq '%');
25 $class->SUPER::new($attribute_name, %options);
36 Perl6Attribute - An example attribute metaclass for Perl 6 style attributes
42 use Class::MOP 'meta';
44 Foo->meta->add_attribute(Perl6Attribute->new('$.foo'));
45 Foo->meta->add_attribute(Perl6Attribute->new('@.bar'));
46 Foo->meta->add_attribute(Perl6Attribute->new('%.baz'));
50 bless $class->meta->construct_instance() => $class;
55 This is an attribute metaclass which implements Perl 6 style
56 attributes, including the auto-generating accessors.
58 This code is very simple, we only need to subclass
59 C<Class::MOP::Attribute> and override C<&new>. Then we just
60 pre-process the attribute name, and create the accessor name
61 and default value based on it.
63 More advanced features like the C<handles> trait (see
64 L<Perl6::Bible/A12>) can be accomplished as well doing the
65 same pre-processing approach. This is left as an exercise to
66 the reader though (if you do it, please send me a patch
67 though, and will update this).
71 Stevan Little E<lt>stevan@iinteractive.comE<gt>
73 =head1 COPYRIGHT AND LICENSE
75 Copyright 2006 by Infinity Interactive, Inc.
77 L<http://www.iinteractive.com>
79 This library is free software; you can redistribute it and/or modify
80 it under the same terms as Perl itself.