Perl Multidimensional Array

Perl multidimensional arrays are arrays with more than one dimension. The multi dimensional array is represented in the form of rows and columns, also called Matrix.

They can not hold arrays or hashes, they can only hold scalar values. They can contain references to another arrays or haashes.

Perl Multidimensional Array Matrix Example

Here, we are printing a 3 dimensional matrix by combining three different arrays arr1, arr2 and arr3. These three arrays are merged to make a matrix array final.

Two for loops are used with two control variables $i and $j.

snippet
## Declaring arrays
my @arr1 = qw(0 10 0);
my @arr2 = qw(0 0 20);
my@arr3 = qw(30 0 0);
## Merging all the single dimensional arrays
my @final = (\@arr1, \@arr2, \@arr3);
print "Print Using Array Index\n";
for(my $i = 0; $i <= $#final; $i++){
   # $#final gives highest index from the array
   for(my $j = 0; $j <= $#final ; $j++){
      print "$final[$i][$j] ";
   }
   print "\n";
}

Output:

Output
Print Using Array Index 0 10 0 0 0 20 30 0 0

Perl Multidimensional Array Initialization and Declaration Example

In this example we are initializing and declaring a three dimensional Perl array .

snippet
@array = (
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
      );
      for($i = 0; $i < 3; $i++) {
    for($j = 0; $j < 3; $j++) {
        print "$array[$i][$j] ";
   }
   print "\n";
}

Output:

Output
1 2 3 4 5 6 7 8 9
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents