Perl Programming Page 3 - Hash Mania With Perl |
If you've actually tested the samples above, you'll have noticed that the hashes printed out in seemingly random order. This is because hashes are stored based on memory location, not alphabetically or numerically. But have heart, it's easy to sort hashes. There are 3 ways to sort in Perl: ASCIIbetically, numerically or alphabetically. Every character (number, letter or metacharacters) has an ASCII code associated with it. Letters have separate ASCII codes for each of the cases (upper and lower case). For example, the letter A is 065 and the letter a is 097. So A is "less than" a (065 < 097). with this in mind, let's create a simple hash that uses both upper and lower cases in its keys: %hash = ( Apples => 1, apples => 4, artichokes => 3, Beets => 9, ); foreach my $key (sort keys %hash) { print "$key = $hash{$key} "; } The above code will print: Apples = 1 Beets = 9 apples = 4 artichokes = 3 Because the letter B is 066 in ASCII code, it is "less than" 097, the letter for A. This yields some strange results, but you may wish to use it one day :) "To sort strings without regard to case, run $a and $b through lc before comparing:" using the cmp comparison operator. This tells Perl to sort letters and ignore case. This correctly prints: Apples = 1 apples = 4 artichokes = 3 Beets = 9 Hash Slices "A slice is a section or number of elements from a list, array or hash." Essentially, you can add or delete key/value pairs en masse using slices, which are named using the @ at symbol. To give an example of slices, consider the following: Here, we've just created a hash named %monthsnum using a hash slice. It added each of the elements of the @months array as keys, and the values are 1 through 12 to each month. Because @months are in order, adding 1 through 12 assigns the correct month number value to each key. So you've done the hash slice and now want to print out the results to make sure it's correct. Prints: Jan = 1 Feb = 2 Mar = 3 Apr = 4 May = 5 Jun = 6 Jul = 7 Aug = 8 Sep = 9 Oct = 10 Nov = 11 Dec = 12 We've already seen how to sort hashes in Sorting Hashes above, and we've just added to it. sorts the hash numerically based on the values of the hash instead of the keys. This way, our months appear in the correct year order.
blog comments powered by Disqus |
|
|
|
|
|
|
|