Perl | Multidimensional Arrays

14 Sep, 2021
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.
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 = ([...], [...], [...]);. 
Perl
#!/usr/bin/perluse strict;use warnings; # Initializing and defining the arraymy @items = ( ['book', 'pen', 'pencil'],              ['Bat', 'Ball', 'Stumps'],              ['snake', 'rat', 'rabbit'] ); # Printing items from the arrayprint $items[0][0], "\n";print $items[1][1], "\n";print $items[2][2], "\n";
Output: 
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. 
Perl
#!/usr/bin/perluse strict;use warnings; # Array Declarationmy @arrayA = qw(1 0 0); my @arrayB = qw(0 1 0); my @arrayC = qw(0 0 1);  # Merging 3 arrays into One Final array my @result = (\@arrayA, \@arrayB, \@arrayC);  print "Resultant 3*3 Matrix:\n";  # Using For loopfor(my $m = 0; $m <= $#result; $m++){     for(my $n = 0; $n <= $#result ; $n++)   {       print "$result[$m][$n] ";    }    print "\n"; } 
Output: 
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. 
Perl
#!usr/bin/perluse strict;use warnings; my (@MatrixA, @MatrixB, @Resultant) = ((), (), ()); # Asking for User Input for Matrix Aprint "Please Provide the order of MatrixA :\n";print "\tMatrixA rows:";chomp(my $rowA = <>);  # CHOMP TO TAKE USER INPUTprint "\tMatrixA columns:";chomp(my $columnA = <>); # Asking for User Input for Matrix Bprint "Please Provide the order of MatrixB :\n";print "\tMatrixB rows:";chomp(my $rowB = <>);print "\tMatrixB columns:";chomp(my $columnB = <>); # Asking User to input elements of matricesif ($rowA == $rowB and $columnA == $columnB){    print "Enter $rowA * $columnA elements in MatrixA:\n";    foreach my $m (0..$rowA - 1)    {        foreach my $n (0..$columnA - 1)        {            chomp($MatrixA[$m][$n] = <>);  # TO READ THE VALUES        }    }         print "Enter $rowB * $columnB elements in MatrixB:\n";    foreach my $m (0..$rowB - 1)    {        foreach my $n (0..$columnB - 1)        {            chomp($MatrixB[$m][$n] = <>);  # TO READ THE VALUES        }    }         # Performing Addition operation    foreach my $m (0..$rowB - 1)    {        foreach my $n (0..$columnB - 1)        {            $Resultant[$m][$n] = $MatrixA[$m][$n] +                                 $MatrixB[$m][$n];        }    }         # Printing Matrix A    print "MatrixA is :\n";    foreach my $m (0..$rowB - 1)    {        foreach my $n (0..$columnB - 1)        {            print "$MatrixA[$m][$n] ";        }        print "\n";    }         # Printing Matrix B    print "MatrixB is :\n";    foreach my $m (0..$rowB - 1)    {        foreach my $n (0..$columnB - 1)        {            print "$MatrixB[$m][$n] ";        }        print "\n";    }         # Printing the sum of Matrices    print "SUM of MatrixA and MatrixB is :\n";    foreach my $m (0..$rowB - 1)    {        foreach my $n (0..$columnB - 1)        {            print "$Resultant[$m][$n] ";        }        print "\n";    }} # Error if Matrices are of different orderelse{    print "Matrices order does not MATCH, Addition is not Possible";}
Output: 
Addition of Matrices can only be performed if the matrices are of the same order.  
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:  
Perl
#!/usr/bin/perluse strict;use warnings; # Array of Arraysmy @GfG = ( ["Geek",  "For",  "Geeks"],            ["Is",    "Best", "For"],            ["Those", "In",  "Need"] ); # Printing internal array elementsprint "Accessing Array elements:\n";print  @{$GfG[0]}[1], "\n"; # For accessing particular array elementprint  @{$GfG[1]}[0], "\n";print  @{$GfG[2]}[2], "\n"; # Printing whole Arraysprint "\nAccessing whole arrays: \n";print @{$GfG[0]}, "\n"; # For accessing particular arrayprint @{$GfG[1]}, "\n";print @{$GfG[2]}, "\n";print "\n";
Output: 
Example 2: 
In this example, we generated an array of array by using a single array.  
Perl
#!/usr/bin/perluse strict;use warnings;use Data::Dumper; my @GfG = ( ["SAM",  "SHABANAM",  "SOHAM"],            ["DHONI", "GONI", "AVNI"],            ["VIRAT", "STUART", "ROHIT"] );my @test;foreach (@GfG){    if ($_ =~ /M/ )    {        push ( @{$test[0]}, $_);    }    elsif ($_ =~ /I/ )    {        push ( @{$test[1]}, $_);    }    else    {        push ( @{$test[2]}, $_);    }} print Dumper(\@test), "\n";
Output: 
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:  
Perl
#!/usr/bin/perluse strict;use warnings; my @hashtest = ({ First => "Geek",                  Middle => "For",                  Last => "Geeks" },                { Street => "Royal Kapsons",                  City => "Noida-Uttar Pradesh" },                { About => "Computer Science portal",                  Content => "Technical" }); # To access any of the hash reference.print $hashtest[0], "\n"; # To access keys of any hash reference.print keys %{$hashtest[2]}, "\n"; # To access any value of any key.print $hashtest[0]->{"First"}, "\n";print $hashtest[0]->{"Middle"}, "\n";print $hashtest[0]->{"Last"}, "\n";
Output: 
Example 2: Generating an array of hashes from a simple array. 
Perl
#!/usr/bin/perluse strict;use warnings; use Data::Dumper; my @array = ("Item - Java Course",             "Cost - 5000",             "Ratings - 5 star"); # Empty array of hashesmy @array_1; foreach (@array){    my @array = split(" - ", $_);    $array_1[0]->{$array[0]} = $array[1];} print Dumper (\@array_1);
Output: 
 
anikakapoor
Perl-Arrays
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | length() Function
Perl | Subroutines or Functions
Perl | Boolean Values
Perl | Basic Syntax of a Perl Program
Introduction to Perl