The Perl way for something like that is called an AoA (Array of Array). The first dimension consists entirely of pointers and the data is in the attached arrays - this just like it is done in the 'C' language.
update: added another example. I also will point out that data types within an AoA can be mixed - this can't be done in C! But in Perl it is perfectly ok and used quite often. Maybe a row is like: ("Smith", "Bob", 1932, $ref2otherdata)!
#!/usr/bin/perl -w
use strict;
my @a = ([1,2,3],
[9,8,7,6,5]);
print "$a[0][1] the 2 in first row\n";
print "$a[1][3] the 6 in the second row\n";
print "showing another way to make a 2-d thing\n";
# often the syntax that allows access to individual elements just
# isn't used as often processing a whole row at once is what is needed
my $rows = 3;
my $cols = 4;
my @x;
while ($rows--)
{
my @rand;
push(@rand, int rand(100)) foreach (1..$cols);
push (@x, [@rand]);
}
foreach my $array_ref (@x)
{
print "@$array_ref\n";
}
__END__
prints:
2 the 2 in first row
6 the 6 in the second row
62 44 73 13
11 14 23 73
47 22 40 9
These arrays like @a can of course be built dynamically and the number of
columns in each row do not have to be equal - this is called a "ragged array" although here they are. Above shows one way to generate a AoA and note that I didn't use any kind of [x][y] coordinates to either generate the 2-D array or to print it. Perl is designed to do thinks like process the entire row easily.
There are other types of Perl data structures that can represent data like what
you have given us a hint about and some of these are less obviously 'C' like. It would be helpful if you could provide some
additional application data. An AoH is also used often and gets away from stuff like index3 means "name" and avoids this #define name 3 sort of statements or their equivalents that are so prevalent in other languages. Anyway if you have heterogeneous stuff stored in the 2D array, there are some cool ways to deal with that.
|