Chapter 5. Hashes
Doing linear scans over an associative array is like trying to club someone to death with a loaded Uzi.
Introduction
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. The relationship encoded in a hash is that of the genitive case or the possessive, like the word “of " in English, or like “’s”. We could encode that the boss of Nat is Tim. Hashes only give convenient ways to access values for Nat’s boss; you can’t ask whose boss Tim is. Finding the answer to that question is a recipe in this chapter.
Fortunately, hashes have their own special 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 to build indices and quick lookup tables.
Only use the %
when referring ...
Get Perl Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.