List Data and Variables

If scalar data is defined as being made up of individual things, then you can think of list data as a collective thing—or, more rightly, as a collection of scalar things. Just as the term scalar data can include both numbers and strings, the term list data usually refers to one of two specific things: arrays and hashes.

We'll talk about arrays today and go deeper into hashes tomorrow on Day 5, “Working with Hashes.”

An array is a collection of any number of scalar things. Each individual thing, or element, can be accessed by referring to the number of its position in the array (its index). Array indexes in Perl start from 0. Figure 4.1 shows an illustration of a simple array with some numbers and strings in it.

Figure 4.1. Anatomy of an Array.


Arrays are ordered, which means they have a first element, last element, and all the elements in between in a specific order. You can change the order of elements in an array by sorting it, or iterate over the elements one at a time, from start to finish.

Arrays are stored in array variables, just like scalars are stored in scalar variables. An array variable starts with the at sign (@). Beyond the first character, array variables have the same rules as far as names go:

  • Names can be up to 255 characters long, and can contain numbers, letters, and underscores.

  • Names are case sensitive; upper and lowercase characters are different.

  • Array variables, unlike scalar variables, can start with a number, but can then only contain other numbers.

In addition, scalar and array variable names do not conflict with each other. The scalar variable $x is a different variable from the array variable @x.

In addition to list data being stored and accessed in an array, list data also has a raw form called, appropriately, a list. A list is simply an ordered set of elements. You can assign a list to a variable, iterate over it to print each of its elements, nest it inside another list, or use it as an argument to a function. Usually, you'll use lists to create arrays and hashes, or to pass data between a list and other lists. In many cases, you can think of lists and arrays being essentially interchangeable.

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

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