HTML CSS PHP PERL

Hour 7. Hashes

 
Previous Table of Contents Next

Hour 7. Hashes

What You'll Learn in This Hour:

The hash is the third basic data type in Perl. The first data type you learned about was the scalar, which is a simple data type designed to hold one thing (any one thingof any sizebut still one thing). Next came the array, which is a collection of scalars. An array can hold as many scalars as you like, but searching for the scalar value you need in an array usually involves sequential access of the array until you find the scalar you need.

Hashes are another kind of collective data type. Like arrays, hashes contain a number of scalars. The difference between arrays and hashes is that hashes access their scalar data by name, not by using a numeric subscript as arrays do. Hash elements have two parts: a key and a value. The key identifies each element of the hash, and the value is the data associated with that key. This relationship is called a key-value pair.

Many applications lend themselves to this type of data structure naturally. For example, if you wanted to store information on licensed drivers in a state, you might use the drivers' license numbers as logical keys to store the license information; these numbers are unique (per driver). The data associated with each number would be the driver's information (license type, address, age, and so on). Each driver's license would represent an element in the hash, with the number and information as the key-value pair. Other data structures that have a hash nature are inventory part numbers, hospital patient records, telephone billing records, disk file systems, music CD-ROM collections, Rolodex information, Library of Congress numbers and ISB Ns (International Standard Book Numbers), and countless others.

A hash in Perl can contain as many elements as you like, or at least as many as the available memory on your system will allow. Hashes are resized as elements are added and deleted from the hash. Access to individual elements in the hash is extremely fast and does not degrade significantly as the hash gets larger. As a result, Perl is comfortable (and quick) with your hash whether it has 10 elements or 100,000 elements. The keys to the hash can be as long as you want (they're just scalars), and the data portions of the hash can also be as large as you want.

Historically, hashes were called associative arrays in Perl and other languages. This term is a long-winded way of indicating that keys were associated with a value. Because Perl programmers aren't much for long-windedness, associative arrays are now simply called hashes.

Hash variables are indicated in Perl by the percent sign (%). They do not share names with arrays and scalars. You can have, for example, a hash named %a, an array named @a, and a scalar named $a. Each of these names refers to one variable unrelated to the others.

    Previous Table of Contents Next
    © 2000- NIV