Debian Codegraph @

README

raw
1 NAME
2 Hash::Ordered - A fast, pure-Perl ordered hash class
3
4 VERSION
5 version 0.014
6
7 SYNOPSIS
8 use Hash::Ordered;
9
10 my $oh = Hash::Ordered->new( a => 1 );
11
12 $oh->get( 'a' );
13 $oh->set( 'a' => 2 );
14
15 $oh->exists( 'a' );
16 $val = $oh->delete( 'a' );
17
18 @keys = $oh->keys;
19 @vals = $oh->values;
20 @pairs = $oh->as_list
21
22 $oh->push( c => 3, d => 4 );
23 $oh->unshift( e => 5, f => 6 );
24
25 ( $k, $v ) = $oh->pop;
26 ( $k, $v ) = $oh->shift;
27
28 $iter = $oh->iterator;
29 while( ( $k, $v ) = $iter->() ) { ... }
30
31 $copy = $oh->clone;
32 $subset = $oh->clone( qw/c d/ );
33 $reversed = $oh->clone( reverse $oh->keys );
34
35 @value_slice = $oh->values( qw/c f/ ); # qw/3 6/
36 @pairs_slice = $oh->as_list( qw/f e/ ); # qw/f 6 e 5/
37
38 $oh->postinc( 'a' ); # like $oh{a}++
39 $oh->add( 'a', 5 ); # like $oh{a} += 5
40 $oh->concat( 'a', 'hello' ); # like $oh{a} .= 'hello'
41 $oh->or_equals( 'g', '23' ); # like $oh{g} ||= 23
42 $oh->dor_equals( 'g', '23' ); # like $oh{g} //= 23
43
44 DESCRIPTION
45 This module implements an ordered hash, meaning that it associates keys
46 with values like a Perl hash, but keeps the keys in a consistent order.
47 Because it is implemented as an object and manipulated with method
48 calls, it is much slower than a Perl hash. This is the cost of keeping
49 order.
50
51 However, compared to other ordered hash implementations, Hash::Ordered
52 is optimized for getting and setting individual elements and is
53 generally faster at most other tasks as well. For specific details, see
54 Hash::Ordered::Benchmarks.
55
56 METHODS
57 new
58 $oh = Hash::Ordered->new;
59 $oh = Hash::Ordered->new( @pairs );
60
61 Constructs an object, with an optional list of key-value pairs.
62
63 The position of a key corresponds to the first occurrence in the list,
64 but the value will be updated if the key is seen more than once.
65
66 Current API available since 0.009.
67
68 clone
69 $oh2 = $oh->clone;
70 $oh2 = $oh->clone( @keys );
71
72 Creates a shallow copy of an ordered hash object. If no arguments are
73 given, it produces an exact copy. If a list of keys is given, the new
74 object includes only those keys in the given order. Keys that aren't in
75 the original will have the value "undef".
76
77 keys
78 @keys = $oh->keys;
79 $size = $oh->keys;
80
81 In list context, returns the ordered list of keys. In scalar context,
82 returns the number of elements.
83
84 Current API available since 0.005.
85
86 values
87 @values = $oh->values;
88 @values = $oh->values( @keys );
89
90 Returns an ordered list of values. If no arguments are given, returns
91 the ordered values of the entire hash. If a list of keys is given,
92 returns values in order corresponding to those keys. If a key does not
93 exist, "undef" will be returned for that value.
94
95 In scalar context, returns the number of elements.
96
97 Current API available since 0.006.
98
99 get
100 $value = $oh->get("some key");
101
102 Returns the value associated with the key, or "undef" if it does not
103 exist in the hash.
104
105 set
106 $oh->set("some key" => "some value");
107
108 Associates a value with a key and returns the value. If the key does not
109 already exist in the hash, it will be added at the end.
110
111 exists
112 if ( $oh->exists("some key") ) { ... }
113
114 Test if some key exists in the hash (without creating it).
115
116 delete
117 $value = $oh->delete("some key");
118
119 Removes a key-value pair from the hash and returns the value.
120
121 clear
122 $oh->clear;
123
124 Removes all key-value pairs from the hash. Returns undef in scalar
125 context or an empty list in list context.
126
127 Current API available since 0.003.
128
129 push
130 $oh->push( one => 1, two => 2);
131
132 Add a list of key-value pairs to the end of the ordered hash. If a key
133 already exists in the hash, it will be deleted and re-inserted at the
134 end with the new value.
135
136 Returns the number of keys after the push is complete.
137
138 pop
139 ($key, $value) = $oh->pop;
140 $value = $oh->pop;
141
142 Removes and returns the last key-value pair in the ordered hash. In
143 scalar context, only the value is returned. If the hash is empty, the
144 returned key and value will be "undef".
145
146 unshift
147 $oh->unshift( one => 1, two => 2 );
148
149 Adds a list of key-value pairs to the beginning of the ordered hash. If
150 a key already exists, it will be deleted and re-inserted at the
151 beginning with the new value.
152
153 Returns the number of keys after the unshift is complete.
154
155 shift
156 ($key, $value) = $oh->shift;
157 $value = $oh->shift;
158
159 Removes and returns the first key-value pair in the ordered hash. In
160 scalar context, only the value is returned. If the hash is empty, the
161 returned key and value will be "undef".
162
163 merge
164 $oh->merge( one => 1, two => 2 );
165
166 Merges a list of key-value pairs into the ordered hash. If a key already
167 exists, its value is replaced. Otherwise, the key-value pair is added at
168 the end of the hash.
169
170 as_list
171 @pairs = $oh->as_list;
172 @pairs = $oh->as_list( @keys );
173
174 Returns an ordered list of key-value pairs. If no arguments are given,
175 all pairs in the hash are returned. If a list of keys is given, the
176 returned list includes only those key-value pairs in the given order.
177 Keys that aren't in the original will have the value "undef".
178
179 iterator
180 $iter = $oh->iterator;
181 $iter = $oh->iterator( reverse $oh->keys ); # reverse
182
183 while ( my ($key,$value) = $iter->() ) { ... }
184
185 Returns a code reference that returns a single key-value pair (in order)
186 on each invocation, or the empty list if all keys are visited.
187
188 If no arguments are given, the iterator walks the entire hash in order.
189 If a list of keys is provided, the iterator walks the hash in that
190 order. Unknown keys will return "undef".
191
192 The list of keys to return is set when the iterator is generator. Keys
193 added later will not be returned. Subsequently deleted keys will return
194 "undef" for the value.
195
196 preinc
197 $oh->preinc($key); # like ++$hash{$key}
198
199 This method is sugar for incrementing a key without having to call "set"
200 and "get" explicitly. It returns the new value.
201
202 Current API available since 0.005.
203
204 postinc
205 $oh->postinc($key); # like $hash{$key}++
206
207 This method is sugar for incrementing a key without having to call "set"
208 and "get" explicitly. It returns the old value.
209
210 Current API available since 0.005.
211
212 predec
213 $oh->predec($key); # like --$hash{$key}
214
215 This method is sugar for decrementing a key without having to call "set"
216 and "get" explicitly. It returns the new value.
217
218 Current API available since 0.005.
219
220 postdec
221 $oh->postdec($key); # like $hash{$key}--
222
223 This method is sugar for decrementing a key without having to call "set"
224 and "get" explicitly. It returns the old value.
225
226 Current API available since 0.005.
227
228 add
229 $oh->add($key, $n); # like $hash{$key} += $n
230
231 This method is sugar for adding a value to a key without having to call
232 "set" and "get" explicitly. With no value to add, it is treated as "0".
233 It returns the new value.
234
235 Current API available since 0.005.
236
237 subtract
238 $oh->subtract($key, $n); # like $hash{$key} -= $n
239
240 This method is sugar for subtracting a value from a key without having
241 to call "set" and "get" explicitly. With no value to subtract, it is
242 treated as "0". It returns the new value.
243
244 Current API available since 0.005.
245
246 concat
247 $oh->concat($key, $str); # like $hash{$key} .= $str
248
249 This method is sugar for concatenating a string onto the value of a key
250 without having to call "set" and "get" explicitly. It returns the new
251 value. If the value to append is not defined, no concatenation is done
252 and no warning is given.
253
254 Current API available since 0.005.
255
256 or_equals
257 $oh->or_equals($key, $str); # like $hash{$key} ||= $str
258
259 This method is sugar for assigning to a key if the existing value is
260 false without having to call "set" and "get" explicitly. It returns the
261 new value.
262
263 Current API available since 0.005.
264
265 dor_equals
266 $oh->dor_equals($key, $str); # like $hash{$key} //= $str
267
268 This method is sugar for assigning to a key if the existing value is not
269 defined without having to call "set" and "get" explicitly. It returns
270 the new value.
271
272 Current API available since 0.005.
273
274 OVERLOADING
275 Boolean
276 if ( $oh ) { ... }
277
278 When used in boolean context, a Hash::Ordered object is true if it has
279 any entries and false otherwise.
280
281 String
282 say "$oh";
283
284 When used in string context, a Hash::Ordered object stringifies like
285 typical Perl objects. E.g. "Hash::Ordered=ARRAY(0x7f815302cac0)"
286
287 Current API available since 0.005.
288
289 Numeric
290 $count = 0 + $oh;
291
292 When used in numeric context, a Hash::Ordered object numifies as the
293 decimal representation of its memory address, just like typical Perl
294 objects. E.g. 140268162536552
295
296 For the number of keys, call the "keys" method in scalar context.
297
298 Current API available since 0.005.
299
300 Fallback
301 Other overload methods are derived from these three, if possible.
302
303 TIED INTERFACE
304 Using "tie" is slower than using method calls directly. But for
305 compatibility with libraries that can only take hashes, it's available
306 if you really need it:
307
308 tie my %hash, "Hash::Ordered", @pairs;
309
310 If you want to access the underlying object for method calls, use
311 "tied":
312
313 tied( %hash )->unshift( @data );
314
315 Tied hash API available since 0.005.
316
317 CAVEATS
318 Deletion and order modification with push, pop, etc.
319 This can be expensive, as the ordered list of keys has to be updated.
320 For small hashes with no more than 25 keys, keys are found and spliced
321 out with linear search. As an optimization for larger hashes, the first
322 change to the ordered list of keys will construct an index to the list
323 of keys. Thereafter, removed keys will be marked with a "tombstone"
324 record. Tombstones will be garbage collected whenever the number of
325 tombstones exceeds the number of valid keys.
326
327 These internal implementation details largely shouldn't concern you. The
328 important things to note are:
329
330 * The costs of efficient deletion are deferred until you need it
331
332 * Deleting lots of keys will temporarily appear to leak memory until
333 garbage collection occurs
334
335 MOTIVATION
336 For a long time, I used Tie::IxHash for ordered hashes, but I grew
337 frustrated with things it lacked, like a cheap way to copy an IxHash
338 object or a convenient iterator when not using the tied interface. As I
339 looked at its implementation, it seemed more complex than I though it
340 needed, with an extra level of indirection that slows data access.
341
342 Given that frustration, I started experimenting with the simplest thing
343 I thought could work for an ordered hash: a hash of key-value pairs and
344 an array with key order.
345
346 As I worked on this, I also started searching for other modules doing
347 similar things. What I found fell broadly into two camps: modules based
348 on tie (even if they offered an OO interface), and pure OO modules. They
349 all either lacked features I deemed necessary or else seemed
350 overly-complex in either implementation or API.
351
352 Hash::Ordered attempts to find the sweet spot with simple
353 implementation, reasonably good efficiency for most common operations,
354 and a rich, intuitive API.
355
356 After discussions with Mario Roy about the potential use of
357 Hash::Ordered with MCE, I optimized deletion of larger hashes and
358 provided a tied interface for compatibility. Mario's suggestions and
359 feedback about optimization were quite valuable. Thank you, Mario!
360
361 SEE ALSO
362 This section describes other ordered-hash modules I found on CPAN. For
363 benchmarking results, see Hash::Ordered::Benchmarks.
364
365 Tie modules
366 The following modules offer some sort of tie interface. I don't like
367 ties, in general, because of the extra indirection involved over a
368 direct method call. Still, you can make any tied interface into a faster
369 OO one with "tied":
370
371 tied( %tied_hash )->FETCH($key);
372
373 Tie::Hash::Indexed is implemented in XS and thus seems promising if
374 pure-Perl isn't a criterion; it generally fails tests on Perl 5.18 and
375 above due to the hash randomization change. Despite being XS, it is
376 slower than Hash::Ordered at everything exception creation and deletion.
377
378 Tie::IxHash is probably the most well known and includes an OO API.
379 Given the performance problems it has, "well known" is the only real
380 reason to use it.
381
382 These other modules below have very specific designs/limitations and I
383 didn't find any of them suitable for general purpose use:
384
385 * Tie::Array::AsHash — array elements split with separator; tie API
386 only
387
388 * Tie::Hash::Array — ordered alphabetically; tie API only
389
390 * Tie::InsertOrderHash — ordered by insertion; tie API only
391
392 * Tie::LLHash — linked-list implementation; quite slow
393
394 * Tie::StoredOrderHash — ordered by last update; tie API only
395
396 Other ordered hash modules
397 Other modules stick with an object-oriented API, with a wide variety of
398 implementation approaches.
399
400 Array::AsHash is essentially an inverse implementation from
401 Hash::Ordered. It keeps pairs in an array and uses a hash to index into
402 the array. This indirection would already make hash-like operations
403 slower, but the specific implementation makes it even worse, with
404 abstractions and function calls that make getting or setting individual
405 items up to 10x slower than Hash::Ordered.
406
407 However, "Array::AsHash" takes an arrayref to initialize, which is very
408 fast and can return the list of pairs faster, too. If you mostly create
409 and list out very large ordered hashes and very rarely touch individual
410 entries, I think this could be something to very cautiously consider.
411
412 These other modules below have restrictions or particularly complicated
413 implementations (often relying on "tie") and thus I didn't think any of
414 them really suitable for use:
415
416 * Array::Assign — arrays with named access; restricted keys
417
418 * Array::OrdHash — overloads array/hash deref and uses internal tied
419 data
420
421 * Data::Pairs — array of key-value hashrefs; allows duplicate keys
422
423 * Data::OMap — array of key-value hashrefs; no duplicate keys
424
425 * Data::XHash — blessed, tied hashref with doubly-linked-list
426
427 SUPPORT
428 Bugs / Feature Requests
429 Please report any bugs or feature requests through the issue tracker at
430 <https://github.com/dagolden/Hash-Ordered/issues>. You will be notified
431 automatically of any progress on your issue.
432
433 Source Code
434 This is open source software. The code repository is available for
435 public review and contribution under the terms of the license.
436
437 <https://github.com/dagolden/Hash-Ordered>
438
439 git clone https://github.com/dagolden/Hash-Ordered.git
440
441 AUTHOR
442 David Golden <[email protected]>
443
444 CONTRIBUTORS
445 * Andy Lester <[email protected]>
446
447 * Benct Philip Jonsson <[email protected]>
448
449 * Mario Roy <[email protected]>
450
451 COPYRIGHT AND LICENSE
452 This software is Copyright (c) 2014 by David Golden.
453
454 This is free software, licensed under:
455
456 The Apache License, Version 2.0, January 2004
457