home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

5.10. Sorting a Hash

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";
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.