Chapter 9. Arrays and Lists

This chapter presents some of Perl’s most useful built-in types, arrays and lists.

Lists and Arrays Are Sequences

Like strings, lists and arrays are sequences of values. In a string, the values are characters; in a list or in an array, they can be any type. The values in a list or in an array are called elements or sometimes items.

There are several important differences between lists and arrays. The main ones are that lists are ordered and immutable collections of items: you can’t change the number of items in a list and you can’t change the individual items either. Arrays, by contrast, are variables and are generally mutable: you can add elements to an array, or remove elements from it. And you can access the individual elements of an array and modify them. For this to be possible, arrays usually have a name (as do other variables), although some arrays are anonymous, which means that they have no name, but have some other ways of accessing them.

A list is also ephemeral (unless it is assigned to a variable or some other thing): it ceases to exist as soon as it has been used, usually as soon as the program control flow goes to the next code line. An array, on the other hand, has some form of persistence: you may be able to use it somewhere else in the program if the variable containing it is still within scope.

There are several ways to create a new list; the simplest is to enumerate its values, separated by commas:

> 3, 4, 5 (3 4 5) > say (3, 4, ...

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.