next up previous
Next: Some Useful Array Functions Up: Basic Perl Programming Previous: Scalar Variables

Arrays

What is an Array?

An array, in Perl, is an ordered list of scalar data.

Each element of an array is an separate scalar variable with a independent scalar value -- unlike PASCAL or C.

Arrays can therefore have mixed elements, for example

(1,"fred", 3.5)

is perfectly valid.

Literal Arrays

Arrays can be defined literally in Perl code by simply enclosing the array elements in parentheses and separating each array element with a comma.

For example

(1, 2, 3)  
("fred", "albert")  
() # empty array (zero elements)
(1..5) # shorthand for (1,2,3,4,5)

Indexed Arrays

You declare an ordinary indexed array by giving it a name and prefixing it with a @

Values are assigned to arrays in the usual fashion:

@array = (1,2,3);

@copy_array = @array;

@one_element = 1; 
# not an error but create the array (1)

Arrays can also be referenced in the literal list, for example:

@array1 = (4,5,6);

@array2 = (1,2,3, @array1, 7,8);

results in the elements of array1 being inserted in the appropriate parts of the list.

Therefore after the above operations

@array2 = (1,2,3,4,5,6,7,8)

This means Lists cannot contain other lists elements only scalars allowed.

Elements of arrays are indexed by index:

$array1[1] = $array2[3];

Assign ``third'' element of array2 to ``first'' element of array1.

Each array element is a scalar so we reference each array element with $.

BIG WARNING:

Array indexing starts from 0 in Perl (like C).

So

@array = (1,2,3,4,5,6,7,8);

The index $array[0] refers to 1 and $array[5] refers to 6.

If you assign a scalar to an array the scalar gets assigned the length of the array, i.e:

@array2 = (1,2,3,4,5,6,7,8);

$length = @array2; # length = 8

$length = $array2[3]; 
# length gets ``third'' value 
# in array i.e 4


next up previous
Next: Some Useful Array Functions Up: Basic Perl Programming Previous: Scalar Variables
Dave Marshall
9/28/2001