Complex Data Structures

We now want to use references to build some higher level data structures.

Two-Dimensional Arrays

Suppose you want to build an array with two dimensions. Conceptually, you might think of this as rows and columns, but Perl thinks of this as an array of arrays. A first attempt may result in something like

@a1 = (10,20,30);
@a2 = (100,200,300);
@matrix = (@a1, @a2);

but this simply creates one flat array with six elements.

print "@matrix"; # prints 10,20,30,100,200,300

Instead, you could populate an array with references to anonymous arrays. See the folder TwoDim.

 % type twodim.pl # # twodim.pl # @twodim = ( [10, 20, 30], [40, 50, 60], [70, 80, 90] ); print "@twodim\n"; print "$twodim[0]\n"; print "$twodim[1]\n"; print ...

Get Programming PERL in the .NET Environment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.