@
) are used to store collections of
objects when it makes sense to index those objects by number. Square brackets
([
and ]
) are used to specify the index or indices of the
elements you are interested in. When the value inside the square brackets is
a single number, or a variable which evaluates to a single number, you should
refer to the variable with a dollar sign, not an at sign, since such an
expression is referring to a scalar value. On the other hand, when the value
inside the square brackets is a list, the expression will refer to another
array of elements (sometimes referred to as a slice), and the at sign is once
again appropriate.
You can initialize an array by separating the array elements with commas, and surrounding them with parentheses:
@values = (1,4,7,9);The following expressions show some of the ways you can access array elements:
$x = $values[0]; # sets x equal to 1 $i = 2; print $values[$i]; # prints 7 @xodd = @values[1,3]; # sets xodd equal to (4,9) @indices = (1,3) @xodd = @values[@indices]; # same as previous @xodd valueNote that either a number or a variable containing a number can be used as a subscript of an array. In fact, any expression which results in a number or an array of numbers can be used as a subscript.