Chapter 10. Hashes

This chapter presents another built-in type called a hash. Hashes are one of Perl’s best and most commonly used features; they are the building blocks of many efficient and elegant algorithms.

A Hash Is a Mapping

A hash is like an array, but more general. In an array, the indices or subscripts have to be integers; in a hash, they can be (almost) anything.

A hash contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. A key and a value together form a pair (an object of the Pair type), or a key-value pair. A hash can be viewed as a collection of key-value pairs. The values in a hash can also be called items or elements, as with arrays.

In other programming languages, hashes are sometimes called dictionaries, hash tables, maps, or associative arrays.

In mathematical language, a hash represents a mapping from keys to values, so you can also say that each key “maps to” a value. As an example, we’ll build a hash that maps from English to Spanish words, so the keys and the values are all strings.

In Perl, hash names start with the “%” sigil. To create a new hash, you just declare it this way:

> my %eng2sp;

This creates an empty hash. To add items to the hash, you can use curly braces (a.k.a. curly brackets or sometimes simply “curlies”):

> %eng2sp{'one'} = 'uno';
uno

This line creates an item that maps from the key 'one' to the value 'uno'.

If the key is a string containing a single word (i.e., without ...

Get Think Perl 6 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.