Chapter 3. Lists and Arrays

If a scalar is the “singular” in Perl, as we described it at the beginning of Chapter 2, the “plural” in Perl is represented by lists and arrays.

A list is an ordered collection of scalars. An array is a variable that contains a list. People tend to use the terms interchangeably, but there’s a big difference. The list is the data and the array is the variable that stores the data. You can have a list value that isn’t in an array, but every array variable holds a list (although that list may be empty). Figure 3-1 represents a list, whether it’s stored in an array or not.

Since lists and arrays share many of the same operations, just like scalar values and variables do, we’ll treat them in parallel. Don’t forget their differences though.

A list with five elements
Figure 3-1. A list with five elements

Each element of an array or list is a separate scalar value. These values are ordered—that is, they have a particular sequence from the first to the last element. The elements of an array or a list are indexed by small integers starting at zero[63] and counting by ones, so the first element of any array or list is always element zero.

Since each element is an independent scalar value, a list or array may hold numbers, strings, undef values, or any mixture of different scalar values. Nevertheless, it’s common to have all elements of the same type, such as a list of book titles (all strings) ...

Get Learning Perl, 6th 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.