VOOZH about

URL: https://www.geeksforgeeks.org/perl/perl-multidimensional-arrays/

⇱ Perl | Multidimensional Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perl | Multidimensional Arrays

Last Updated : 12 Jul, 2025

Multidimensional arrays in Perl are the arrays with more than one dimension. Technically there is no such thing as a multidimensional array in Perl but arrays are used to act as they have more than one dimension. Multi dimensional arrays are represented in the form of rows and columns, also knows as matrix. Each element of an array can be a reference to another array but in syntax, they will appear like a 2-dimensional array. 

A multidimensional array can only hold scalar values, they can not hold arrays or hashes.

Initialization and Declaration of a Multidimensional Array

Given below is the example that makes clear the initialization and declaration of a Multidimensional array. 
In this example we will simply initialize the array by @array_name = ([...], [...], [...]);

Output: 

πŸ‘ Image

Creating a Matrix

Matrix is a collection of rows and columns of arrays that appears to be in more than one dimension. 
Let's see an example to make it more clear of creating a matrix in Perl.

Example 1: 
In this example, we first declared three arrays with values and then merged them into a final resulted array to form a 3*3 matrix. In order to control the variable $m and $n, two for loops are used. 

Output: 

πŸ‘ Image


Example 2: 
In this example, we will take the input from the keyboard and then add the two matrices and printing the result using the resultant matrix. 

Output: 

πŸ‘ Image

Addition of Matrices can only be performed if the matrices are of the same order.  

πŸ‘ Image

Array of Arrays

Array of Arrays are the data structures having an array having list of array references. Elements inside an array are the array references. These references can be printed individually or the whole array can be printed as well, as per the requirement. 

Syntax: 

@ARRAY_NAME = ([value1], [value2], [value3], ..., [valueN]);

Example 1:  

Output: 

πŸ‘ Image

Example 2: 

In this example, we generated an array of array by using a single array.  

Output: 

πŸ‘ Image

Array of Hashes

Array of hashes is the data structure where the array has a list of hashes. Hash references are the objects of an array. In order to access the key and values, we need to de-reference them. 
Array of hashes is a great data structure if we want to loop through hashes numerically. 

Syntax:  

@ARRAY_NAME = ({KEY1 => VALUE1}, {KEY2 => VALUE2});

Example 1:  

Output: 

πŸ‘ Image

Example 2: 
Generating an array of hashes from a simple array. 

Output: 

πŸ‘ Image


 

Comment
Article Tags:
Article Tags:

Explore