< BACKCONTINUE >

B.6 Arrays

Arrays are ordered collections of zero or more scalar values, indexed by position. An array variable begins with the at sign @ followed by a legal variable name. For instance, here are two possible array variable names:

@array1
@dna_fragments

You can assign scalar values to an array by placing the scalar values in a list, separated by commas and surrounded by a pair of parentheses. For instance, you can assign an array the empty list:

@array = (  );

or one or more scalar values:

@dna_fragments = ('ACGT', $fragment2, 'GGCGGA');

Notice that it's okay to specify a scalar variable such as $fragment2 in a list. Its current value, not the variable name, is placed into the array.

The individual scalar values of an array (the elements) are indexed by their position in the array. The index numbers begin at 0. You can specify the individual elements of an array by preceding the array name by a $ and following it with the index number of the element within square brackets [ ], like so:

$dna_fragments[2]

This equals the value of 'GGCGGA', given the values previously set for this array. Notice that the array has three scalar values, indexed by numbers 0, 1, and 2. The third and last element is indexed 2, one less than the total number of elements 3, because the first element is indexed number 0.

You can make a copy of an array using an assignment operator =, as in this example that makes a copy @output of an existing array @input:

@output = @input;

If you evaluate an array in scalar context, the value is the number of elements in the array. So if array @input has five elements, the following example assigns the value 5 to $count:

$count = @input;

Figure B-1 shows an array @myarray with three elements, which demonstrates the ordered nature of an array; by which each element appears, and can be found by its position in the array.

Figure B-1. Schematic of an array
< BACKCONTINUE >

Index terms contained in this section

arrays
copying
      arrays
elements, array
      specifying individual
indexing
      scalar values in arrays
Perl
      arrays
positions in arrays
scalar context
      arrays in
scalar values
      assigning to arrays

© 2002, O'Reilly & Associates, Inc.