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 set
128 $hash->set($key [, $value ... ]);
129
130 Changes the stored value(s) of the given $key. This removes or adds
131 pairs as necessary to store the new list but otherwise preserves
132 order of existing pairs. "$hash->{$key}" is updated to point to the
133 last value.
134
135 add
136 $hash->add($key, $value [, $value ... ]);
137
138 Appends a new value to the given $key. This updates the value of
139 "$hash->{$key}" as well so it always points to the last value.
140
141 remove
142 $hash->remove($key);
143
144 Removes a key and associated values for the given $key.
145
146 clear
147 $hash->clear;
148
149 Clears the hash to be an empty hash reference.
150
151 flatten
152 @pairs = $hash->flatten;
153
154 Gets pairs of keys and values. This should be exactly the same
155 pairs which are given to "new" method unless you updated the data.
156
157 each
158 $hash->each($code);
159
160 # e.g.
161 $hash->each(sub { print "$_[0] = $_[1]\n" });
162
163 Calls $code once for each "($key, $value)" pair. This is a more
164 convenient alternative to calling "flatten" and then iterating over
165 it two items at a time.
166
167 Inside $code, $_ contains the current iteration through the loop,
168 starting at 0. For example:
169
170 $hash = Hash::MultiValue->new(a => 1, b => 2, c => 3, a => 4);
171
172 $hash->each(sub { print "$_: $_[0] = $_[1]\n" });
173 # 0: a = 1
174 # 1: b = 2
175 # 2: c = 3
176 # 3: a = 4
177
178 Be careful not to change @_ inside your coderef! It will update
179 the tracking object but not the plain hash. In the future, this
180 limitation may be removed.
181
182 clone
183 $new = $hash->clone;
184
185 Creates a new Hash::MultiValue object that represents the same
186 data, but obviously not sharing the reference. It's identical to:
187
188 $new = Hash::MultiValue->new($hash->flatten);
189
190 as_hashref
191 $copy = $hash->as_hashref;
192
193 Creates a new plain (unblessed) hash reference where a value is a
194 single scalar. It's identical to:
195
196 $copy = +{%$hash};
197
198 as_hashref_mixed, mixed
199 $mixed = $hash->as_hashref_mixed;
200 $mixed = $hash->mixed;
201
202 Creates a new plain (unblessed) hash reference where the value is a
203 single scalar, or an array ref when there are multiple values for a
204 same key. Handy to create a hash reference that is often used in
205 web application frameworks request objects such as Catalyst. Ths
206 method does exactly the opposite of "from_mixed".
207
208 as_hashref_multi, multi
209 $multi = $hash->as_hashref_multi;
210 $multi = $hash->multi;
211
212 Creates a new plain (unblessed) hash reference where values are all
213 array references, regardless of there are single or multiple values
214 for a same key.
215
216 from_mixed
217 $hash = Hash::MultiValue->from_mixed({
218 foo => [ 'a', 'b' ],
219 bar => 'c',
220 });
221
222 Creates a new object out of a hash reference where the value is
223 single or an array ref depending on the number of elements. Handy
224 to convert from those request objects used in web frameworks such
225 as Catalyst. This method does exactly the opposite of
226 "as_hashref_mixed".
227
229 You might wonder why this module uses the last value of the same key
230 instead of first. There's no strong reasoning on this decision since
231 one is as arbitrary as the other, but this is more consistent to what
232 Perl does:
233
234 sub x {
235 return ('a', 'b', 'c');
236 }
237
238 my $x = x(); # $x = 'c'
239
240 my %a = ( a => 1 );
241 my %b = ( a => 2 );
242
243 my %m = (%a, %b); # $m{a} = 2
244
245 When perl gets a list in a scalar context it gets the last entry. Also
246 if you merge hashes having a same key, the last one wins.
247
249 If you pass this MultiValue hash object to some upstream functions that
250 you can't control and does things like:
251
252 if (ref $args eq 'HASH') {
253 ...
254 }
255
256 because this is a blessed hash reference it doesn't match and would
257 fail. To avoid that you should call "as_hashref" to get a finalized (=
258 non-blessed) hash reference.
259
260 You can also use UNIVERSAL::ref to make it work magically:
261
262 use UNIVERSAL::ref; # before loading Hash::MultiValue
263 use Hash::MultiValue;
264
265 and then all "ref" calls to Hash::MultiValue objects will return HASH.
266
268 Prior to version 0.09, this module wasn't safe in a threaded
269 environment, including win32 fork() emulation. Versions newer than 0.09
270 is considered thread safe.
271
273 Tatsuhiko Miyagawa <miyagawa@bulknews.net>
274
275 Aristotle Pagaltzis
276
277 Hans Dieter Pearcey
278
279 Thanks to Michael Peters for the suggestion to use inside-out objects
280 instead of tie.
281
283 This library is free software; you can redistribute it and/or modify it
284 under the same terms as Perl itself.
285
287 • <http://pythonpaste.org/webob/#multidict>
288
289 • Tie::Hash::MultiValue
290
291
292
293perl v5.32.1 2021-01-27 Hash::MultiValue(3)