next up previous contents index
Next: Hashes Up: Variables Previous: HERE syntax   Contents   Index


Arrays

There may be situations where you have a collection of variables which share a common theme - for example, a group of names in a class, or a set of test scores. In such cases representing this data by a group of scalar variables, such as $score_1, $score_2, ..., may be inconvenient. In such cases an array might be of use.

An array is denoted by @array_name, with the name of the array following the same rules as for scalar variables. Individual members of an array are accessed through an integer index, which starts at 0, and can be accessed through the syntax $array_name[$index_number]. For example,

  @scores = (4, 6, 10, 12);
  print $scores[2];
will print out the value 10. The fact that array indices start at 0 is confusing at first (it has it's origins in the way arrays are represented in memory), but one quickly (more or less) gets used to it.

There are two ways to obtain the size of the array. One is to use the special variable $#array_name, which has the value of the last index in the array. Note that this is 1 less than the number of elements in the array, since array indices begin at 0. Another way is to use an assignment $size = scalar @array_name, which will assign $size to the number of elements in @array_name (ie, $#array_name + 1).

There are four useful functions available to populate arrays.


next up previous contents index
Next: Hashes Up: Variables Previous: HERE syntax   Contents   Index