This is part 10 of my series, Basics of ActivePerl. A hash is like an array, but not exactly the same. In this part of the tutorial we look at the hash of ActivePerl.
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
A Hash Content Example
The following list shows some fruits and their colors:
Apple => purple
Banana => yellow
Pear => green
Lemon => green
In the list we see that apple is purple, banana is yellow, etc. The => sign just shows that the item on the left corresponds to the item on the right. This is a hash list. Let us look at a typical array list; a list of first names of some employees in a firm:
0 John
1 Mary
2 Peter
3 Augustine
4 Angela
5 Susan
6 Martin
In the array list the first column must always be indices; while the second column can have numbers or strings. In a hash list the first column is not necessarily indices; it can be made up of numbers and/or strings; the second column can also be made up of numbers and/or strings. The difference between a hash list and an array list is that for an array list the first column always consists of indices (counting numbers from zero), but for a hash list the first column can be numbers and/or strings. The second column for an array or hash list can be anything (numbers and/or strings). For the above two examples, the hash list has strings for the first column and the array list has its unconditional indices. The rest of this tutorial will deal with hashes.
Creating a Hash
The syntax to create a hash is:
my %hashName = (key1 => value1, key2 => value2, key3 => value3, ...);
You begin with the reserved word, my, then a space. Next you have the symbol %, followed by the name of the hash. The hash name preceded by % is the hash variable. After that you have the assignment operator. Then you have the hash list in parentheses (brackets). Looking at the hash example above, the first column is called the keys; the second column is called the values. You type them as such inside the parentheses. Each hash element inside the brackets begins with the key, followed by the => sign (i.e. the equal sign followed by the greater than sign), then the corresponding value. Before you type the next element, you have to type a comma first. Of course, the last element does not have a comma before the closing brackets. Well, after the closing brackets you have the semicolon; which indicates the end of an ActivePerl statement. If the value is a string it is typed in the brackets in quotes (single or double). If the value is a number, it is not typed in quotes.
You can give the name, fruitColor to the fruit example above. The following statement creates the hash in ActivePerl:
my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green");
Note that in the brackets the keys are not in quotes. The above statement can be typed in your code neatly as follows:
my %fruitColor = (
Apple => "purple",
Banana => "yellow",
Pear => "green",
Lemon => "green"
);
Accessing a Hash Value
The syntax to access a hash value is:
$hashName{'key'}
You begin with a $ symbol, followed by the hash name, and then a pair of curly braces. Inside the curly braces, you have the key (in single or double quotes) of the corresponding value. So to access the purple string above, you would type:
$fruitColor{'Apple'}
In this expression the key has to be in quotes, (single or double). However, when creating the hash the keys are not in quotes. This expression returns the corresponding value for the key.
Changing a Hash Value
You use the above expression to change a hash value as follows:
$hashName{'key'} = newValue;
So to change the color of the apple in the hash from purple to red, you would type:
$fruitColor{'Apple'}= "red";
Read and try the following code, where the initial color for apple is displayed and then changed and re-displayed.
use strict;
print "Content-Type: text/html\n\n";
my %fruitColor = (
Apple => "purple",
Banana => "yellow",
Pear => "green",
Lemon => "green"
);
print $fruitColor{'Apple'}; print "
";
$fruitColor{'Apple'}= "red";
print $fruitColor{'Apple'};
Accessing with a variable in place of a Key
You can access a value with a variable in place of a key. The following code segment illustrates this:
my $herKey = 'Apple';
print $fruitColor{$herKey};
Hash Functions
The Hash has functions just as the array has functions. We look at some hash functions below.
The each Function
The syntax to use the each function is:
each (%HashName)
This expression returns either the next key/value pair or the next key depending on what is called the list context or scalar context. In our code below it is the next key/value pair that will be returned. In the code below, I use the hash above with four elements. So if you use the each function four times you will have the four different key/value pairs. Read and try the following code:
use strict;
print "Content-Type: text/html\n\n";
my %fruitColor = (
Apple => "purple",
Banana => "yellow",
Pear => "green",
Lemon => "green"
);
print each (%fruitColor); print "
";
print each (%fruitColor); print "
";
print each (%fruitColor); print "
";
print each (%fruitColor); print "
";
In my computer I had the following output:
Bananayellow
Applepurple
Lemongreen
Peargreen
Well, the key and value for each pair are not separated; let us not worry about that for now. The order of the key/value pairs is not the same order in which we typed them in the hash. Just note that this order cannot be predetermined. So the each function will return the next key/value pair under certain conditions. It begins with what it considers as the first, then if it is called again, it returns what it considers as the next, and so on. You the ActivePerl programmer cannot know the order in which the elements will be returned.
The keys Function
The syntax of the keys function is:
keys (%hashName)
It returns a list (which can be held by an array) of all keys in a hash. Read and try the following code:
use strict;
print "Content-Type: text/html\n\n";
my %fruitColor = (
Apple => "purple",
Banana => "yellow",
Pear => "green",
Lemon => "green"
);
my @arr = keys (%fruitColor);
print @arr;
The order of the return keys again is not predetermined (not the way they were typed).
The values Function
The syntax for the values function is:
values(%hashName)
The values function behaves in a similar way to the keys function except that it returns a list of the values in the hash and not a list of the keys. Read and try the following code:
use strict;
print "Content-Type: text/html\n\n";
my %fruitColor = (
Apple => "purple",
Banana => "yellow",
Pear => "green",
Lemon => "green"
);
my @arr = values(%fruitColor);
print @arr;
Again the order of the returned values is not predetermined.
Note on using Functions
With functions like the ones we have seen, the space between the function name e.g. each or keys and the open bracket is optional. That is you do not have to type the space. The two brackets themselves, which enclose certain items after the function name are also optional; that is you do not have to typed these brackets. However, it is a good habit to type the brackets as it makes your coding similar to coding of other computer languages.
The hash has other functions, but we shall not go into that in this basic tutorial. We end here and continue in the next part of the series.
Chrys
Published by Chrys Forcha
I have more than 10 years experience in computer programming, software, electronics and telecommunications. I have a First Degree in Electronics and a Master's Degree in Technical Education. As well a... View profile
200 USDA Approved Menus for Child Care CentersThis article will provide 200 USDA approved menus for the busy child care provider that are quick and easy to prepare.- Presenting Healthy, Artistic and Creative Food for KidsYou will learn to transform plain grocery store items into exquisite, healthy works of art that your children will make and enjoy eating. Colorful links to photos and videos are included.
Facts About Avocados: Healthy and GreenAvocados come in over 80 varieties. Here's just a few and some facts on how good they are for you.
Go Green and Save Money by Creating an Edible LandscapeAn edible landscape can save you money at the grocery store, plus give you a garden that utilizes precious resources more effectively.- Antique French Country Key CabinetCreating a French Country antique paint finish on a Key Cabinet is an easy project that can be accomplished in one weekend.
- All About Wine: Everything You Need to Know, Quite Literally
- Regular Expressions in Perl for the Novice
- How to Prepare and Eat Exotic Fruits and Vegetables
- Peruvian Cuisine - Delicious and Diverse
- How to Install and Configure Apache on Windows Vista to Run Perl Scripts
- The Link Between Acidic Foods and Interstitial Cystitis
- Fruits and Vegetables: Five a Day for Good Health



