next up previous contents
Next: Some Useful Array Functions Up: Arrays Previous: Literal Arrays

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



dave@cs.cf.ac.uk