1Hash::MultiValue(3) User Contributed Perl Documentation Hash::MultiValue(3)
2
3
4
6 Hash::MultiValue - Store multiple values per key
7
9 use Hash::MultiValue;
10
11 my $hash = Hash::MultiValue->new(
12 foo => 'a',
13 foo => 'b',
14 bar => 'baz',
15 );
16
17 # $hash is an object, but can be used as a hashref and DWIMs!
18 my $foo = $hash->{foo}; # 'b' (the last entry)
19 my $foo = $hash->get('foo'); # 'b' (always, regardless of context)
20 my @foo = $hash->get_all('foo'); # ('a', 'b')
21
22 keys %$hash; # ('foo', 'bar') not guaranteed to be ordered
23 $hash->keys; # ('foo', 'foo', 'bar') guaranteed to be ordered
24
26 Hash::MultiValue is an object (and a plain hash reference) that may
27 contain multiple values per key, inspired by MultiDict of WebOb.
28
30 In a typical web application, the request parameters (a.k.a CGI
31 parameters) can be single value or multi values. Using CGI.pm style
32 "param" is one way to deal with this problem (and it is good, as long
33 as you're aware of its list context gotcha), but there's another
34 approach to convert parameters into a hash reference, like Catalyst's
35 "$c->req->parameters" does, and it sucks.
36
37 Why? Because the value could be just a scalar if there is one value and
38 an array ref if there are multiple, depending on user input rather than
39 how you code it. So your code should always be like this to be
40 defensive:
41
42 my $p = $c->req->parameters;
43 my @maybe_multi = ref $p->{m} eq 'ARRAY' ? @{$p->{m}} : ($p->{m});
44 my $must_single = ref $p->{m} eq 'ARRAY' ? $p->{m}->[0] : $p->{m};
45
46 Otherwise you'll get a random runtime exception of Can't use string as
47 an ARRAY ref or get stringified array ARRAY(0xXXXXXXXXX) as a string,
48 depending on user input and that is miserable and insecure.
49
50 This module provides a solution to this by making it behave like a
51 single value hash reference, but also has an API to get multiple values
52 on demand, explicitly.
53
55 The object returned by "new" is a blessed hash reference that contains
56 the last entry of the same key if there are multiple values, but it
57 also keeps the original pair state in the object tracker (a.k.a inside
58 out objects) and allows you to access the original pairs and multiple
59 values via the method calls, such as "get_all" or "flatten".
60
61 This module does not use "tie" or overload and is quite fast.
62
63 Yes, there is Tie::Hash::MultiValue and this module tries to solve
64 exactly the same problem, but using a different implementation.
65
67 When you update the content of the hash, DO NOT UPDATE using the hash
68 reference interface: this won't write through to the tracking object.
69
70 my $hash = Hash::MultiValue->new(...);
71
72 # WRONG
73 $hash->{foo} = 'bar';
74 delete $hash->{foo};
75
76 # Correct
77 $hash->add(foo => 'bar');
78 $hash->remove('foo');
79
80 See below for the list of updating methods.
81
83 new
84 $hash = Hash::MultiValue->new(@pairs);
85
86 Creates a new object that can be treated as a plain hash reference
87 as well.
88
89 get
90 $value = $hash->get($key);
91 $value = $hash->{$key};
92
93 Returns a single value for the given $key. If there are multiple
94 values, the last one (not first one) is returned. See below for
95 why.
96
97 Note that this always returns the single element as a scalar,
98 regardless of its context, unlike CGI.pm's "param" method etc.
99
100 get_one
101 $value = $hash->get_one($key);
102
103 Returns a single value for the given $key. This method croaks if
104 there is no value or multiple values associated with the key, so
105 you should wrap it with eval or modules like Try::Tiny.
106
107 get_all
108 @values = $hash->get_all($key);
109
110 Returns a list of values for the given $key. This method always
111 returns a list regardless of its context. If there is no value
112 attached, the result will be an empty list.
113
114 keys
115 @keys = $hash->keys;
116
117 Returns a list of all keys, including duplicates (see the example
118 in the "SYNOPSIS").
119
120 If you want only unique keys, use "keys %$hash", as normal.
121
122 values
123 @values = $hash->values;
124
125 Returns a list of all values, in the same order as "$hash->keys".
126
127 add
128 $hash->add($key, $value [, $value ... ]);
129
130 Appends a new value to the given $key. This updates the value of
131 "$hash->{$key}" as well so it always points to the last value.
132
133 remove
134 $hash->remove($key);
135
136 Removes a key and associated values for the given $key.
137
138 clear
139 $hash->clear;
140
141 Clears the hash to be an empty hash reference.
142
143 flatten
144 @pairs = $hash->flatten;
145
146 Gets pairs of keys and values. This should be exactly the same
147 pairs which are given to "new" method unless you updated the data.
148
149 each
150 $hash->each($code);
151
152 # e.g.
153 $hash->each(sub { print "$_[0] = $_[1]\n" });
154
155 Calls $code once for each "($key, $value)" pair. This is a more
156 convenient alternative to calling "flatten" and then iterating over
157 it two items at a time.
158
159 Inside $code, $_ contains the current iteration through the loop,
160 starting at 0. For example:
161
162 $hash = Hash::MultiValue->new(a => 1, b => 2, c => 3, a => 4);
163
164 $hash->each(sub { print "$_: $_[0] = $_[1]\n" });
165 # 0: a = 1
166 # 1: b = 2
167 # 2: c = 3
168 # 3: a = 4
169
170 Be careful not to change @_ inside your coderef! It will update
171 the tracking object but not the plain hash. In the future, this
172 limitation may be removed.
173
174 clone
175 $new = $hash->clone;
176
177 Creates a new Hash::MultiValue object that represents the same
178 data, but obviously not sharing the reference. It's identical to:
179
180 $new = Hash::MultiValue->new($hash->flatten);
181
182 as_hashref
183 $copy = $hash->as_hashref;
184
185 Creates a new plain (unblessed) hash reference where a value is a
186 single scalar. It's identical to:
187
188 $copy = +{%$hash};
189
190 as_hashref_mixed, mixed
191 $mixed = $hash->as_hashref_mixed;
192 $mixed = $hash->mixed;
193
194 Creates a new plain (unblessed) hash reference where the value is a
195 single scalar, or an array ref when there are multiple values for a
196 same key. Handy to create a hash reference that is often used in
197 web application frameworks request objects such as Catalyst. Ths
198 method does exactly the opposite of "from_mixed".
199
200 as_hashref_multi, multi
201 $multi = $hash->as_hashref_multi
202 $multi = $hash->multi
203
204 Creates a new plain (unblessed) hash reference where values are all
205 array references, regardless of there are single or multiple values
206 for a same key.
207
208 from_mixed
209 $hash = Hash::MultiValue->from_mixed({
210 foo => [ 'a', 'b' ],
211 bar => 'c',
212 });
213
214 Creates a new object out of a hash reference where the value is
215 single or an array ref depending on the number of elements. Handy
216 to convert from those request objects used in web frameworks such
217 as Catalyst. This method does exactly the opposite of
218 "as_hashref_mixed".
219
221 You might wonder why this module uses the last value of the same key
222 instead of first. There's no strong reasoning on this decision since
223 one is as arbitrary as the other, but this is more consistent to what
224 Perl does:
225
226 sub x {
227 return ('a', 'b', 'c');
228 }
229
230 my $x = x(); # $x = 'c'
231
232 my %a = ( a => 1 );
233 my %b = ( a => 2 );
234
235 my %m = (%a, %b); # $m{a} = 2
236
237 When perl gets a list in a scalar context it gets the last entry. Also
238 if you merge hashes having a same key, the last one wins.
239
241 If you pass this MultiValue hash object to some upstream functions that
242 you can't control and does things like:
243
244 if (ref $args eq 'HASH') {
245 ...
246 }
247
248 because this is a blessed hash reference it doesn't match and would
249 fail. To avoid that you should call "as_hashref" to get a finalized (=
250 non-blessed) hash reference.
251
252 You can also use UNIVERSAL::ref to make it work magically:
253
254 use UNIVERSAL::ref; # before loading Hash::MultiValue
255 use Hash::MultiValue;
256
257 and then all "ref" calls to Hash::MultiValue objects will return HASH.
258
260 Tatsuhiko Miyagawa <miyagawa@bulknews.net>
261
262 Aristotle Pagaltzis
263
264 Hans Dieter Pearcey
265
266 Thanks to Michael Peters for the suggestion to use inside-out objects
267 instead of tie.
268
270 This library is free software; you can redistribute it and/or modify it
271 under the same terms as Perl itself.
272
274 · <http://pythonpaste.org/webob/#multidict>
275
276 · Tie::Hash::MultiValue
277
278
279
280perl v5.12.0 2010-02-11 Hash::MultiValue(3)