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