Perl Programming Page 4 - Hash Mania With Perl |
Think it will introduce too many typos to remember the construct for alphabetical sorting? Then "sub" it! Let's say you use sorting very frequently in your programming and find it cumbersome to type in the above operations each time. Let's handle this by example: You can easily see that the lc($a) cmp lc($b) has been replaced by a subroutine call. Now, let's consider the following: The ascend_alphanum and descend_alphanum routines sort both alphabetically and numerically, so if you added "5 Spice Seasoning", "1 Star Flour", and "911 Hot Sauce" to %hash, it will sort the numbers numerically in addition to letters alphabetically. Apples = 1 apples = 4 artichokes = 3 Beets = 9 canadian = 9 5 Spice Seasoning = 1 10 Star Flour = 1 911 Hot Sauce = 1 Working with Hash References Have a hash reference and don't want to duplicate the subroutines to deal with them? It's easy... just pass the dereferenced keys to the sort routines: Notice the hash deference %{$hashref} and the arrow dereferencer for the value $hashref->{$key}. Sorting by Hash Values What if you wanted to sort the values instead of the keys? Consider the following: This will print out: Apples = 1 5 Spice Seasoning = 1 10 Star Flour = 1 APples = 2 artichokes = 3 apples = 4 911 Hot Sauce = 4 canadian = 9 Beets = 9 But let's say you also had text values -- let's change $hash{'Beets'} to "cans: 4 - 8.oz." and $hash{'Apples'} to "Delicious Red - 4 medium sized". You can have the hash sorted numerically and alphabetically by using the following: This will correctly print out: Beets = cans: 4 - 8.oz. Apples = Delicious Red - 4 medium sized 5 Spice Seasoning = 1 10 Star Flour = 1 APples = 2 artichokes = 3 apples = 4 911 Hot Sauce = 4 canadian = 9 Multidimensional Hashes Using key/value pairs is great, but what if you wanted to associate more than one value to a key? Using a slightly different construct, you can essentially use an array as a key's value: Now, to extract the values, you can treat them as an array of the hash: ...will print package, because package is the second element of Canadian Bacon's "array". You can also add an predefined array to a hash value: But what if @garlicstuff had more elements than others? Let's say that @garlicstuff is instead? How do we print out all values for a key if one key can have 3 values, and another has 4 (or more) values? Because a multidimensional array's values are essentially arrays, a key's group of values can be dereferenced by using @{$hash{$key}}. The above code prints: 10 Star Flour: 1 package 16 oz. 5 Spice Seasoning: 1 bottle 3 oz. 911 Hot Sauce: 1 bottle 8 oz. Apples: 4 Delicious red medium artichokes: 3 cans 8.oz. Beets: 4 cans 8.oz. Canadian Bacon: 1 package 1/2 pound Garlic: 4 cloves medium chopped
blog comments powered by Disqus |
|
|
|
|
|
|
|