You are doing GREAT for just starting!
First, multi-dimensional data structure consists of only references until you get to the last dimension. An ArrayOfArray is what the name says, an array of references to arrays. Earlier I think I saw a 2D structure that you built with a hash for the first dimension. That is not the usual case as you don't get easy sequential processing with a hash. But sometimes this is useful. In that case this is a HashOfArray, or hash of references to arrays.
Below is some code that makes both types and returns a reference to each one. There are no limits on the size of the AoA or HoA. I do a split to get @row from the data line. The default split is on 'space',\t\f\r\t so this also gets rid of the end of line (no need for chomp). Then I just push a reference to this row array onto the AoA and to the HoA. One line of code for each one.
Whenever your code encounters a "my" variable statement. You are guaranteed to get a "new one". Perl will reuse the space the last one used or if it can't because a reference to it is in existence, new memory will be allocated.
#!/usr/bin/perl -w
use strict;
use Data::Dump qw(pp);
my ($arrayRef, $hashRef) = makeBothTypes();
sub makeBothTypes
{
my $rowName = 'A';
my @twoDarray;
my %twoDhash;
while (<DATA>)
{
my @row = split; # no chomp needed for default split
push @twoDarray, \@row;
$twoDhash{$rowName++} = \@row;
}
return (\@twoDarray,\%twoDhash);
}
print pp($arrayRef);
print pp($hashRef);
print "\n";
print "$hashRef->{B}[2]\n"; #23
print "$arrayRef->[1][2]\n"; #23
=output that this prints....
[
[11, 12, 13, 14, 15, 16, 17],
[21, 22, 23, 24, 25, 26, 27],
[31, 32, 33, 34, 35, 36, 37],
[41, 42, 43, 44, 45, 46, 47],
[51, 52, 53, 54, 55, 56, 57],
]{
A => [11, 12, 13, 14, 15, 16, 17],
B => [21, 22, 23, 24, 25, 26, 27],
C => [31, 32, 33, 34, 35, 36, 37],
D => [41, 42, 43, 44, 45, 46, 47],
E => [51, 52, 53, 54, 55, 56, 57],
}
23
23
=cut
__DATA__
11 12 13 14 15 16 17
21 22 23 24 25 26 27
31 32 33 34 35 36 37
41 42 43 44 45 46 47
51 52 53 54 55 56 57
|