## 2-Dimensional Array in Perl

This example starts with the usual declarations.

```#!/usr/bin/perl -w

use strict;

my (\$width, \$height) = (3, 4);
my (\$x, \$y);
my (@array2d, @rows);```

Now we create the “Y-Axis” array which will give us “height”. Here I set the value to “0”.

```for (\$y = 0; \$y < \$height; \$y++)
{
push @rows, "0";
}```

Then we stuff the “rows” array into the main array. We’re creating an array of arrays.

```for (\$x = 0; \$x < \$width; \$x++)
{
push @array2d, [ @rows ];
}```

That covers creating a two-dimensional array, so let’s test the output to make sure it’s working as expected.

```\$array2d = "1";
print "Just set position (1,3) to value '1'\n";

for (\$y = 0; \$y < \$height; \$y++)
{
for (\$x = 0; \$x < \$width; \$x++)
{
print "(\$x,\$y) => \$array2d[\$x][\$y]\n";
}
}```

Output:

```Just set position (1,3) to value '1'
(0,0) => 0
(1,0) => 0
(2,0) => 0
(0,1) => 0
(1,1) => 0
(2,1) => 0
(0,2) => 0
(1,2) => 0
(2,2) => 0
(0,3) => 0
(1,3) => 1
(2,3) => 0```

Staypressed theme by Themocracy