# Recipe 5.10 Sorting a Hash

#### 5.10.1 Problem

You need to work with the elements of a hash in a particular order.

#### 5.10.2 Solution

Use keys to get a list of keys, then sort them based on the ordering you want:

```# %hash is the hash to sort
@keys = sort { criterion( ) } (keys %hash);
foreach \$key (@keys) {
\$value = \$hash{\$key};
# do something with \$key, \$value
}```

#### 5.10.3 Discussion

Even 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:

```foreach \$food (sort keys %food_color) {
print "\$food is \$food_color{\$food}.\n";
}```

This sorts the keys by their associated values:

```foreach \$food (sort { \$food_color{\$a} cmp \$food_color{\$b} }
keys %food_color)
{
print "\$food is \$food_color{\$food}.\n";
}```

This sorts by length of the values:

```@foods = sort {
length(\$food_color{\$a}) <=> length(\$food_color{\$b})
} keys %food_color;
foreach \$food (@foods) {
print "\$food is \$food_color{\$food}.\n";
}```

The 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

 Chapter 1. Strings
 Chapter 2. Numbers
 Chapter 3. Dates and Times
 Chapter 4. Arrays
 Chapter 6. Pattern Matching
 Chapter 7. File Access
 Chapter 8. File Contents
 Chapter 9. Directories
 Chapter 10. Subroutines
 Chapter 11. References and Records
 Chapter 12. Packages, Libraries, and Modules
 Chapter 13. Classes, Objects, and Ties
 Chapter 14. Database Access
 Chapter 15. Interactivity
 Chapter 16. Process Management and Communication
 Chapter 17. Sockets
 Chapter 18. Internet Services
 Chapter 19. CGI Programming
 Chapter 20. Web Automation
 Chapter 21. mod_perl
 Chapter 22. XML