adding in some more examples
[gitmo/Class-MOP.git] / examples / Perl6Attribute.pm
CommitLineData
e2f8b029 1
2package Perl6Attribute;
3
4use strict;
5use warnings;
6
7our $VERSION = '0.01';
8
9use base 'Class::MOP::Attribute';
10
11sub new {
12 my ($class, $attribute_name, %options) = @_;
13
14 # extract the sigil and accessor name
15 my ($sigil, $accessor_name) = ($attribute_name =~ /^([\$\@\%])\.(.*)$/);
16
17 # pass the accessor name
18 $options{accessor} = $accessor_name;
19
20 # create a default value based on the sigil
21 $options{default} = sub { [] } if ($sigil eq '@');
22 $options{default} = sub { {} } if ($sigil eq '%');
23
24 $class->SUPER::new($attribute_name, %options);
25}
26
271;
28
29__END__
30
31=pod
32
33=head1 NAME
34
35Perl6Attribute - An attribute metaclass for Perl 6 style attributes
36
37=head1 SYNOPSIS
38
39 package Foo;
40
41 use Class::MOP 'meta';
42
43 Foo->meta->add_attribute(Perl6Attribute->new('$.foo'));
44 Foo->meta->add_attribute(Perl6Attribute->new('@.bar'));
45 Foo->meta->add_attribute(Perl6Attribute->new('%.baz'));
46
47 sub new {
48 my $class = shift;
49 bless $class->meta->construct_instance() => $class;
50 }
51
52=head1 DESCRIPTION
53
54This is an attribute metaclass which implements Perl 6 style
55attributes, including the auto-generating accessors.
56
57This code is very simple, we only need to subclass
58C<Class::MOP::Attribute> and override C<&new>. Then we just
59pre-process the attribute name, and create the accessor name
60and default value based on it.
61
62More advanced features like the C<handles> trait (see
63L<Perl6::Bible/A12>) can be accomplished as well doing the
64same pre-processing approach. This is left as an exercise to
65the reader though (if you do it, please send me a patch
66though, and will update this).
67
68=head1 AUTHOR
69
70Stevan Little E<lt>stevan@iinteractive.comE<gt>
71
72=head1 COPYRIGHT AND LICENSE
73
74Copyright 2006 by Infinity Interactive, Inc.
75
76L<http://www.iinteractive.com>
77
78This library is free software; you can redistribute it and/or modify
79it under the same terms as Perl itself.
80
81=cut