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 . 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.

Initializing a hash in Perl

There are two ways to initialize a hash; one is very similar to that of an array:
%hash = (
"key1", "value1", 
"key2", "value2",
"key3", "value3"
 );

Here the hash is initialized from a normal list, taking every two scalars as the key/value pair. The other way is specific to the hash structure:
%hash = (
  key1 => "value1",
  key2 => "value2",
  key3 => "value3", 
  );

The => operator is similar to the comma, but it implicitly quotes the value to the left of it, treating it as a literal string. This is a more convenient method of initializing a hash, and we will use it almost exclusively in this course. Here's an example, using our Best Picture data from the array examples:
The chmod settings for a Perl file on the server must be set to 755.
%bestpix = ( 
   1990 => "Dances with Wolves", 
   1991 => "The Silence of the Lambs",
   1992 => "Unforgiven", 
   1993 => "Schindler's List", 
   1994 => "Forrest Gump",
   1995 => "Braveheart",
   1996 => "The English Patient",
   1997 => "Titanic",
   );

This creates a hash with the year of the award for the key and the title of the film for the value.


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.

SEMrush Software