O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Hashes

In this chapter, you will see a feature that makes Perl one of the world’s great programming languages—hashes.[157] Though hashes are a powerful and useful feature, you may have used other powerful languages for years without ever hearing of hashes. But you’ll use hashes in nearly every Perl program you’ll write from now on; they’re that important.

What Is a Hash?

A hash is a data structure like an array, in that it can hold any number of values and retrieve these values at will. However, instead of indexing the values by number, as we did with arrays, we’ll look up the values by name. That is, the indices (here, we’ll call them keys ) aren’t numbers but are arbitrary unique strings (see Figure 6-1).

The keys are strings, first of all, so instead of getting element number 3 from an array, we’ll be accessing the hash element named wilma.

These keys are arbitrary strings—you can use any string expression for a hash key. And they are unique strings; as there’s only one array element numbered 3, there’s only one hash element named wilma.

Another way to think of a hash is that it’s like a barrel of data (see Figure 6-2), where each piece of data has a tag attached. You can reach into the barrel and pull out any tag and see what piece of data is attached. But there’s no “first” item in the barrel; it’s just a jumble. In an array, we’d start with element 0 and then element 1, element 2, and so on. But in a hash, there’s no fixed order, no first element. It’s just a collection ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required