References and Data Structures

Creating a two-dimensional array - Cont.

A more compact way is to define @data directly as an anonymous data structure:
#!/usr/bin/perl

my @data = ( ['Alex',      'Bob',     'Carl',   'David',   'Erik'    ],
             ['Anne',      'Betty',   'Carol',  'Debby',   'Edna'    ],
             ['Australia', 'Belgium', 'Canada', 'Denmark', 'England' ],
             ['Alligator', 'Bear',    'Cat',    'Dog',     'Elephant'],
                                                                     );
In this example, each list inside square brackets, e.g.
['Anne', 'Betty', 'Carol', 'Debby', 'Edna'] ,
is a reference to an anonymous list of values ('Anne', 'Betty', etc.).

We can even create $struct from scratch, as an anonymous data structure:

#!/usr/bin/perl

my $struct = [ ['Alex',      'Bob',     'Carl',   'David',   'Erik'    ],
               ['Anne',      'Betty',   'Carol',  'Debby',   'Edna'    ],
               ['Australia', 'Belgium', 'Canada', 'Denmark', 'England' ],
               ['Alligator', 'Bear',    'Cat',    'Dog',     'Elephant'],
                                                                         ];
$struct is a reference to an array of references to arrays.

Since $struct is itself a scalar, it will be easy to pass it to/from subroutines.


Table of Contents.
Previous | Next.