1. Technology

Beginning Perl Tutorial - Data Types: Lists

What is a List?


Next: Accessing Array Elements

If a scalar is an empty box, think of a list as a nice neat row of those same empty boxes. A list is simply an ordered group of scalars. The particular order doesn't really matter, in fact you can order it all kinds of ways. The important thing to remember is that there is an order. Perl always knows what order those boxes are in, even if you're not entirely sure, and they're always numbered in a straight line one right after the other, starting with 0. Each box still has it's own special identifier, but they are all part of the group.

Just like the scalar, the list has as special symbol - the @ sign. Otherwise, it has the exact same naming conventions. You may use any combinations of letters, numbers, and the underscore character, but you may not begin a variable name with a number:

You've probably also heard the term array before, too. A list is the actual data itself, and an array is the variable name that holds the list data, like the ones in the example above. Most folks use the words variable and array when talking about scalars and lists respectively.

Putting data into your ordered lists of boxes is accomplished using the same assignment operator you used with the scalar. The only difference is the format of the data you're putting in. List assignments use parentheses to contain the data, like this:

 @myNumbers = (1, 2, 3, 4);
 @myNames = ('Larry', 'Curly', 'Moe'); 
Let's take a look at a real program and see some lists in action.
 @myNumbers = (1, 2, 3, 4, 5);
 print @myNumbers; 
It does exactly what you'd expect after playing with scalars. It simply prints out the entire value of the array in order.
 $ ./simpleProgram.pl
Again, the type of data you store in these lists of scalars doesn't matter. It's perfectly acceptable to mix and match as the situations warrant.
 @myMixedList = (1, 'Moe', 'Curly', 4, 3, 'Larry', 5);
 print "@myMixedList\n"; 
Next: Accessing Array Elements
  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Perl Lists Tutorial and Basic Instructions

©2014 About.com. All rights reserved.