Broad Network


Perl Hash

Perl Basics Part 10

Perl Course

Foreword: A hash is like an array, but not exactly the same. In this part of the series I discuss the Perl hash.

By: Chrysanthus Date Published: 29 Mar 2015

Introduction

This is part 10 of my series, Perl Basics. A hash is like an array, but not exactly the same. In this part of the series I discuss the Perl hash. You should have read the previous parts of the series before reaching here, as this is a continuation.

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 a Perl 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 Perl:

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";

Try the following code, where the initial color for apple is displayed and then changed and re-displayed.

use strict;

my %fruitColor = (
                                 Apple => "purple",
                                 Banana => "yellow",
                                 Pear => "green",
                                 Lemon => "green"
                             );

print $fruitColor{'Apple'}; print "\n";

$fruitColor{'Apple'}= "red";

print $fruitColor{'Apple'};

Creating Empty Array before Assigning Values
You can create an empty array using either of the following statements:

    my %hashName = ();

    my %hashName;

You can then add elements one-by-one as follows:

$fruitColor{'Apple'}= "purple";
$fruitColor{'Banana'}= "yellow";

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;

my %fruitColor = (
                                 Apple => "purple",
                                 Banana => "yellow",
                                 Pear => "green",
                                 Lemon => "green"
                             );

print each (%fruitColor); print "\n";
print each (%fruitColor); print "\n";
print each (%fruitColor); print "\n";
print each (%fruitColor); print "\n";

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 but not necessarily in the original order. 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 Perl 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 the hash. Try the following code:

use strict;

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;

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

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message