Multidimensional Arrays
Let's learn what multidimensional arrays are and learn how to access elements stored in an array in this lesson.
We'll cover the following
What are multidimensional arrays?
Perl allows us to create multidimensional arrays. We can think of these arrays as an extension of the single-dimensional (linear) arrays. For example, two-dimensional arrays can be imagined as a matrix or table containing two dimensions: rows and columns.
Similarly, three-dimensional arrays can be imagined as a cube with three dimensions. Each dimension is represented using []
, with the indices starting from 0
along each dimension. The size of arrays can grow dynamically. Values stored in multidimensional arrays can be of any data type. In the example below, we consider strings:
@comparisonAdjectives= (["good", "better", "best"],["bad", "worse", "worst"],["tall", "taller", "tallest"]);for ($i = 0; $i < 3 ; $i++) {for ($j = 0; $j < 3; $j++) {print $comparisonAdjectives[$i][$j] . " ";}print "\n";}
Accessing values in multidimensional arrays
We can access a particular value from a two-dimensional array using indexes of both dimensions. Indexing in multidimensional arrays starts from the [0][0]
index.
The following visualization presents how to access the third item of the second row of a two-dimensional array.
Run the code below to see how this is done:
@comparisonAdjectives= (["good", "better", "best"],["bad", "worse", "worst"],["tall", "taller", "tallest"]);print $comparisonAdjectives[1][2]; # this will access worst
In the code above, there are indexed rows called $comparisonAdjectives
. This array has three indexed rows inside it. Each indexed row has 3 keys (indexes, in this case) and they start from 0. Each key has an associated value with it. To access the third value of the second row, we use the [1]
index to access the second row, followed by [2]
to access the third value of this row.
Arrays are declared with the
@
symbol before the array name, but their specific element is indexed using the$
symbol before the array name.