Perl Programming Page 5 - Hash Functions |
A very common use of a hash variable is to count things. For instance, we can count the number of characters in a string or the items in an array. Let’s look at counting items in an array. We will create an array of names and then we will count the number of times each name occurs in the array. For instance, for this array: my @names = qw( we see that@namesis a collection of 12 names. Upon close inspection, we see that “John” occurs four times, “Sue” occurs once, and so on. We can use a hash to keep a count of the number of times a name occurs in@namesby creating a hash that will have the names as its keys, and the number of occurrences of the name as the value associated with the key. For instance, when all the names in@namesare processed, we will end up with a hash that resembles John => 4, Here is a program illustrating this concept: #!/usr/bin/perl -w use strict; my @names = qw( my %count; foreach (@names) { foreach (keys %count) { Executing this code produces the following result: $ perl count.pl The most important part of this program is when we loop through the array and keep count: foreach (@names) { This code implements the logic “For each name in the array, if the name already exists in the hash, then increment the value by 1 (incrementing the count); else if it does not exist in the hash, then add the name to the hash with the initial value of 1.” After all the names are processed, then the hash will contain all the names and the number of times that each name is present in@names. For minimalists, theifstatement can be shortened because this logic: if (exists $count{$_}) { is built into the statement $count{$_}++; Therefore, ourforeachloop could be changed to foreach (@names) { or more simply $count{$_}++ foreach @names; Summary Hashes are unordered structures made up of pairs, each pair consisting of a key and a value, and given the key we can look up the value. Generally, Hashes are very useful variables that allow us to create data that is human-readable, reversible, and often used for counting things. Exercises
blog comments powered by Disqus |
|
|
|
|
|
|
|