Ïðèãëàøàåì ïîñåòèòü
Áåñòóæåâ-Ìàðëèíñêèé (bestuzhev-marlinskiy.lit-info.ru)

Hour 4. Stacking Building Blocks: Lists and Arrays

Previous Table of Contents Next

Hour 4. Stacking Building Blocks: Lists and Arrays

What You'll Learn in This Hour:

Scalars are Perl's singular nouns. They can represent any one thing—a word, a record, a document, a line of text, or a character. Often, though, you need to talk about collections of things—many words, a few records, two documents, fifty lines of text, or a dozen characters.

When you need to talk about many things in Perl, you use list data. You can represent list data in three different ways: by using lists, arrays, and hashes.

Lists are the simplest representation of list data. A list is simply a group of scalars. Sometimes they're written with a set of parentheses encasing the scalars, which are separated by commas. For example, (2, 5, $a, "Bob") is a list that contains two numbers, a scalar variable $a, and the string "Bob". Each scalar in a list is called a list element. In keeping with the philosophy of Least Surprise (see Hour 2, "Perl's Building Blocks: Numbers and Strings"), Perl's lists can contain as many scalar elements as you like. Because scalars can also be arbitrarily large, a list can hold quite a lot of data.

To store list data so that you can refer to it throughout your program, you need an array variable. Array variables are represented in Perl with an "at" sign (@) as the type identifier followed by a valid variable name (as discussed in Hour 2, "Perl's Building Blocks: Numbers and Strings"). For example, @foo is a valid array variable in Perl. You can have the same name for an array variable as a scalar variable; for example, $names and @names refer to different things—$names to a scalar variable, and @names to an array. The two variables have nothing to do with each other.

Individual items in an array are called array elements. Individual array elements are referred to by their position within the array, called an index. That is, we can refer to the third array element of the array @foo, the fifth array element of the array @names, and so on.

The other list type, a hash, is similar to an array. Hashes will be discussed further in Hour 7, "Hashes."

    Previous Table of Contents Next