Home arrow Perl Programming arrow Hashes


Hashes in Perl aren't really that hard to understand; they're not that much harder than understanding how a phone book works. This article introduces you to hashes, what they do, and how to use them. It is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).

  1. Hashes
  2. Creating a Hash
  3. Working with Hash Values
  4. Adding, Changing, and Removing Elements
By: Apress Publishing
Rating: starstarstarstarstar / 3
April 29, 2010

print this article



We have talked about two types of data: scalars and arrays. Scalars are single pieces of information, while arrays are single variables containing many different values.

Alternatively, some things are better expressed as a set of one-to-one correspondences. A phone book, for example, is a set of correspondences between addresses and phone numbers. In Perl, structures like the phone book are represented as a hash. Some people call them associative arrays because they look a bit like arrays where each element is associated with another value. Most Perl programmers find that a bit too long-winded, and end up just calling them hashes.

Comparing a hash to a phone book is helpful, but there is a slight difference in that a phone book is normally ordered—the names are sorted alphabetically. In a hash the data is totally unsorted and has no intrinsic order. In fact, it’s more like directory enquiries than a phone book, in that you can easily find out what the number is if you have the name. Someone else keeps the order for you, and you needn’t ask what the first entry is.

Here’s where a diagram helps:

A scalar is one piece of data. It’s like a single block. An array or a list is like a tower of blocks; it’s kept in order, and it’s kept together as a single unit. A hash, on the other hand, is more like the illustration above. It contains several pairs of data. The pairs are in no particular order, no pair is “first” or “top,” and they’re all scattered around the hash.

>>> More Perl Programming Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: