Arrays and List Data

Contents:

What Is a List or Array?

Accessing Elements of an Array

Special Array Indices

List Literals

List Assignment

Interpolating Arrays Into Strings

Scalar and List Context

<STDIN> in List Context

Exercises































What Is a List or Array?

If a scalar was the "singular" in Perl, as described in the previous sessions on scalar variables, 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.  In Perl, the two terms are often used as if they're interchangeable.  But, to be accurate, the list is the data, and the array is the variable.  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).



Array caching graphical tiles in game development

(see http://www.gamedev.net/reference/articles/article847.asp)

Each element of an array or list is an separate scalar variable with an independent 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 list are indexed by small integers starting at zero1 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 most common to have all elements of the same type, such as a list of book titles (all strings) or a list of cosines (all numbers).

To summarize:

A list is ordered scalar data.  An array is a variable that holds a list.  Each element of the array is a separate scalar variable with an independent scalar value.  These values are ordered; that is, they have a particular sequence from the lowest to the highest element.

Arrays can have any number of elements.  The smallest array has no elements, while the largest array can fill all of available memory.  Once again, this is in keeping with Perl's philosophy of "no unnecessary limits."

Next:  Accessing Elements of an Array

OR

Main Menu for this topic





























[1] Array and list indices always start at zero in Perl, unlike in some other languages.  In early Perl is was possible to change the starting number of array and list indexing (not for just one array or list, but for all of them at once!).  Larry later realized that this was a misfeature, and its (ab)use is now strongly discouraged.  But, if you're terminally curious, look up the $[ variable in the perlvar manpage.

Return to the page from whence you came