Hour 4. Stacking Building Blocks: Lists and Arrays

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. Sometimes, though, you need to talk about collections of things—many words, a few records, two documents, 50 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; they're 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 of two numbers, a scalar $a, and the word "Bob". Each item in a list is called a list element. In keeping with the philosophy of Least Surprise, Perl's lists can contain as many elements as you like. And because lists are collections of scalars, and scalars can also be arbitrarily large, lists can hold quite a bit of data.

To store a list in a variable, you need an array variable. Array variables are represented in Perl with an at sign (@) 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, the third array element of the array @FOO or 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".

In this hour you will learn

  • How to fill and empty arrays

  • How to examine arrays element-by-element

  • How to sort and print arrays

  • How to split scalars into arrays, and how to join arrays back into scalars

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.102.178