Perl Programming Page 4 - Hash Functions |
Hashes are very useful variables and there are many uses for them. Here are a few examples of using hashes to solve common problems. Creating Readable Variables The most basic use of a hash is to be able to index into a variable to obtain information using a readable string which is far more user-friendly than using a numeric index as we would with an array. For instance, this program shows that we can create a record of strings representing RGB colors that one might find in an HTML page: #!/usr/bin/perl -w use strict; my %colors = ( print "Red is: $colors{red}\n"; Notice how the information in the hash is laid out in such a way that it is readable by human beings. It is easy to see that the RGB string for “red” is “#FF0000” and indexing into the hash is the human-friendly$colors{red}. Executing this code produces the following: $ perl colors.pl “Reversing” Information Recall the hash we created earlier in this chapter that was a collection of people and where they lived: %where = ( If you need to turn this hash around to look up people by where they live, you can use a hash in list context that produces a list of key/value pairs, reverse the list with thereverse()function, and then assign it to a new hash. %who = reverse %where; Be careful though—if you have two values that are the same, then converting them to keys means that one will be lost. Remember that keys must be unique. Here is a program illustrating reversing a hash: #!/usr/bin/perl -w use strict; my %where = ( my %who = reverse %where; foreach (keys %who) { Executing this code produces the following: $ perl reverse.pl After we assigned to%who, we created a hash indexed by the location producing the name that is the direct opposite of%where, which was indexed by name to produce the location.
blog comments powered by Disqus |
|
|
|
|
|
|
|