add hash slices
[gitmo/Moose-Autobox.git] / lib / Moose / Autobox / Hash.pm
CommitLineData
5f654d8e 1package Moose::Autobox::Hash;
2use Moose::Role 'with';
3
bc9177cb 4use Carp qw(croak);
5
18ef6e1c 6our $VERSION = '0.03';
5f654d8e 7
6cf5bcf2 8with 'Moose::Autobox::Ref',
9 'Moose::Autobox::Indexed';
10
11sub delete {
12 my ($hash, $key) = @_;
13 CORE::delete $hash->{$key};
14}
15
bc9177cb 16sub merge {
17 my ($left, $right) = @_;
18 croak "You must pass a hashref as argument to merge"
19 unless ref $right eq 'HASH';
20 return { %$left, %$right };
21}
22
6cf5bcf2 23# ::Indexed implementation
5f654d8e 24
31d40d73 25sub at {
26 my ($hash, $index) = @_;
27 $hash->{$index};
28}
29
30sub put {
31 my ($hash, $index, $value) = @_;
32 $hash->{$index} = $value;
33}
34
5f654d8e 35sub exists {
36 my ($hash, $key) = @_;
37 CORE::exists $hash->{$key};
38}
e6bb88b0 39
5f654d8e 40sub keys {
41 my ($hash) = @_;
e6bb88b0 42 [ CORE::keys %$hash ];
5f654d8e 43}
44
45sub values {
46 my ($hash) = @_;
e6bb88b0 47 [ CORE::values %$hash ];
48}
49
50sub kv {
51 my ($hash) = @_;
52 [ CORE::map { [ $_, $hash->{$_} ] } CORE::keys %$hash ];
5f654d8e 53}
54
18ef6e1c 55sub slice {
56 my ($hash, $keys) = @_;
57 return [ @{$hash}{@$keys} ];
58};
59
3f4dd8b7 60sub print { CORE::print %{$_[0]} }
61sub say { CORE::print %{$_[0]}, "\n" }
62
31d40d73 631;
64
65__END__
66
67=pod
68
69=head1 NAME
70
71Moose::Autobox::Hash - the Hash role
72
73=head1 SYNOPOSIS
74
75 use Moose::Autobox;
31d40d73 76
8937074a 77 print { one => 1, two => 2 }->keys->join(', '); # prints 'one, two'
31d40d73 78
79=head1 DESCRIPTION
80
8937074a 81This is a role to describes a Hash value.
82
260cc81f 83=head1 METHODS
84
85=over 4
86
260cc81f 87=item B<delete>
88
bc9177cb 89=item B<merge>
90
91Takes a hashref and returns a new hashref with right precedence
92shallow merging.
93
260cc81f 94=back
95
5272f13f 96=head2 Indexed implementation
260cc81f 97
98=over 4
99
100=item B<at>
101
102=item B<put>
103
104=item B<exists>
105
106=item B<keys>
107
108=item B<values>
109
110=item B<kv>
111
18ef6e1c 112=item B<slice>
113
260cc81f 114=back
115
5272f13f 116=over 4
117
118=item B<meta>
119
3f4dd8b7 120=item B<print>
121
122=item B<say>
123
5272f13f 124=back
125
31d40d73 126=head1 BUGS
127
128All complex software has bugs lurking in it, and this module is no
129exception. If you find a bug please either email me, or add the bug
130to cpan-RT.
131
132=head1 AUTHOR
133
134Stevan Little E<lt>stevan@iinteractive.comE<gt>
135
136=head1 COPYRIGHT AND LICENSE
137
ea4e64bf 138Copyright 2006-2008 by Infinity Interactive, Inc.
31d40d73 139
140L<http://www.iinteractive.com>
141
142This library is free software; you can redistribute it and/or modify
143it under the same terms as Perl itself.
144
bc9177cb 145=cut
146