Chapter 5. Hashes

Introduction

Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.

Larry Wall

People and parts of computer programs interact in all sorts of ways. Single scalar variables are like hermits, living a solitary existence whose only meaning comes from within the individual. Arrays are like cults, where multitudes marshal themselves under the name of a charismatic leader. In the middle lies the comfortable, intimate ground of the one-to-one relationship that is the hash. (Older documentation for Perl often called hashes associative arrays , but that’s a mouthful. Other languages that support similar constructs sometimes use different terms for them; you may hear about hash tables, tables, dictionaries, mappings, or even alists, depending on the language.)

Unfortunately, this isn’t a relationship of equals. Hashes are an of relationship, like saying “Andy is the boss of Nat,” “The blood pressure of our patient is 112/62,” and “The name of journal ISSN 1087-903X is The Perl Journal.” Hashes only give convenient ways to access values for “Nat’s boss” and “1087-903X’s name”; you can’t ask “Whose boss is Andy?” Finding the answer to that question is a recipe in this chapter.

Fortunately, hashes have their benefits, just like relationships. Hashes are a built-in data type in Perl. Their use reduces many complex algorithms to simple variable accesses. They are also fast and convenient ways to build indices and quick lookup ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.