5.10. Sorting a Hash5.10.2. SolutionUse keys to get a list of keys, then sort them based on the ordering you want:
5.10.3. DiscussionEven though you can't directly maintain a hash in a specific order (unless you use the Tie::IxHash module mentioned in Recipe 5.7), you can access its entries in any order. This technique offers many variations on the same basic mechanism: you extract the keys, reorder them using the sort function, and then process the entries in the new order. All the sorting tricks shown in Chapter 4 can be used here. Let's look at some applications. The following code simply uses sort to order the keys alphabetically:
This sorts the keys by their associated values:
This sorts by length of the values:
5.10.4. See AlsoThe sort and keys functions in perlfunc(1) and in Chapter 29 of Programming Perl; Recipe 5.7; we discuss sorting lists in Recipe 4.16
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|