Perl Variables  «Prev  Next»
Lesson 13 Perl Hash Functions
ObjectiveHow are hash functions in Perl created and used?

Perl Hash Functions

Oiginally, when Perl was young, a hash was called an associative array. But in today's modern, more enlightened programming society, we simply call it a hash (or, The Artist Formerly Known As The Associative Array, TAFKATAA).

A hash is similar to an array in that it is an aggregation of scalars, but the similarities end there. Just as you access an array with a numeric subscript (or index), you access a hash with a string key.
Additionally, an array is stored in the order in which it was defined, but a hash is not stored in any discernable order at all (in fact, it is stored in an order defined by the internal hashing algorithm as maximally efficient for a binary search).

Perl Keys and values

Each hash element consists of a key and a value, sometimes called a key/value pair. The key is the index for finding the hash element, and the value is the actual value of the element. For the purpose of finding a given entry in the hash, the key is always construed as a string.


Diagram of a hash
Diagram of a hash

Initializing Perl hash

A hash variable is distinguished by using a % character in front of the variable name, like this:
%hash

There are two ways of initializing a hash.

Perl Hash Function - Quiz

Click the Quiz link below to answer a couple of multiple-choice questions with respect to hashes in Perl.
Perl Hash Function - Quiz
In the next lesson, how to access the elements of a hash will be discussed.