Add merge method for hashes.
[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.02';
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 # ::Indexed implementation
24
25 sub at {
26     my ($hash, $index) = @_;
27     $hash->{$index};
28
29
30 sub put {
31     my ($hash, $index, $value) = @_;
32     $hash->{$index} = $value;
33 }
34
35 sub exists { 
36     my ($hash, $key) = @_;
37     CORE::exists $hash->{$key}; 
38 }
39
40 sub keys { 
41     my ($hash) = @_;
42     [ CORE::keys %$hash ];
43 }
44
45 sub values { 
46     my ($hash) = @_;    
47     [ CORE::values %$hash ]; 
48 }
49
50 sub kv {
51     my ($hash) = @_;    
52     [ CORE::map { [ $_, $hash->{$_} ] } CORE::keys %$hash ];    
53 }
54
55 1;
56
57 __END__
58
59 =pod
60
61 =head1 NAME 
62
63 Moose::Autobox::Hash - the Hash role
64
65 =head1 SYNOPOSIS
66
67   use Moose::Autobox;
68   
69   print { one => 1, two => 2 }->keys->join(', '); # prints 'one, two'
70
71 =head1 DESCRIPTION
72
73 This is a role to describes a Hash value. 
74
75 =head1 METHODS
76
77 =over 4
78
79 =item B<delete>
80
81 =item B<merge>
82
83 Takes a hashref and returns a new hashref with right precedence
84 shallow merging.
85
86 =back
87
88 =head2 Indexed implementation
89
90 =over 4
91
92 =item B<at>
93
94 =item B<put>
95
96 =item B<exists>
97
98 =item B<keys>
99
100 =item B<values>
101
102 =item B<kv>
103
104 =back
105
106 =over 4
107
108 =item B<meta>
109
110 =back
111
112 =head1 BUGS
113
114 All complex software has bugs lurking in it, and this module is no 
115 exception. If you find a bug please either email me, or add the bug
116 to cpan-RT.
117
118 =head1 AUTHOR
119
120 Stevan Little E<lt>stevan@iinteractive.comE<gt>
121
122 Anders Nor Berle E<lt>debolaz@gmail.comE<gt>
123
124 =head1 COPYRIGHT AND LICENSE
125
126 Copyright 2006 by Infinity Interactive, Inc.
127
128 L<http://www.iinteractive.com>
129
130 This library is free software; you can redistribute it and/or modify
131 it under the same terms as Perl itself.
132
133 =cut
134