CIW Course Revision Site


Perl - Introduction to Arrays

In a Nutshell - CIW Course Section 2, Part B1, Chapter 5

Arrays Overview

An array is an indexed list of variables. In Perl the indexing starts at element zero, so an array with six elements will number from 0 to 5.

Each element in the array is a scalar variable, so it can hold string, numeric, or Boolean values. Unlike other programming languages, Perl arrays can hold mixed data types so, one element in the array may hold a string value, while another element in the same array holds a numeric value.

Initialising Arrays

In Perl array names are prefixed with the "@" symbol and are initialised by a sinple assignment statement:

@myArray1 = (20, 30, 40, 50);
@myArray2 = ("Tom", "Dick", "Harry");
@myArray3 = ("Tom", 20, "Harry");

An array assignment may also contain an array reference:

@myArray4 = "30, 40, 50);
@myArray5 = "10, 20, @myArray4, 60, 70);

myArray4 remains independent of myArray5, it's values have been copied into myArray5 so the resulting array will have 7 element: 10, 20, 30, 40, 50, 60, 70.

Another trick is to use a range of values in the assignment:

@myArray6 = (1..10, 15, 20);

which will assign the values 1 to 10 inclusive into consecutive elements, followed by the explicit values 15, 20. resulting in an array of 12 elements.

Accessing Array Elements

When accessing individual elements in the array you should remember that each element is a scalar variable, and scalar variable names are prefixed with the "$" symbol.

print ("$myArray2[0]");

So, the above example will yield the result "Tom" as the first item in the list at position element zero.

$#myArray1 returns the last element number in the array, or the array length, to use, perhaps, more familiar jargon. In this example it will return the value "3". This can be useful when adding to the array as $myArray1[$#myArray1 + 1] = 60 will add a new element containing the value "60". There are probably more elegant ways of doing this, but that's for the next chapter.

The array length value is also very useful when using a loop to iterate through all of the elements in the array:

for ($p = 0; $p <= $#myArray1; $p++)
{
  print("$myArray1[$p]\n");
}

Again, there are better ways to achieve this and these are detailed in the next chapter.

 

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011