References and Data Structures

Creating a two-dimensional array

Our first example of a complex data structure will be the creation of a two-dimensional array, which is actually an array of arrays, or a list of lists.

Our example simulates a popular game, where participants have to find names of a a boy, a girl, a country, a city, an animal, a plant etc., that start with a given letter. For simplicity, we will show possible answers for some categories, for letters A-I.

Here is the data we want to store in the 2D-array:

Boy name Alex Bob Carl David Erik Fred Gert Haim Imre
Girl name Anne Betty Carol Debby Edna Francis Gina Hedva Irene
Country Australia Belgium Canada Denmark England France Great Britain Hungary Israel
Animal Alligator Bear Cat Dog Elephant Fox Goose Horse Iguana

One way to build the 2D-array is the following:

#!/usr/bin/perl

# 1. Create an array for each line.

my @boys       = ('Alex',      'Bob',     'Carl',   'David',   'Erik'    ,'Fred',    'Gert',          'Haim',    'Imre');
my @girls      = ('Anne',      'Betty',   'Carol',  'Debby',   'Edna'    ,'Francis', 'Gina',          'Hedva',   'Irene');
my @countries  = ('Australia', 'Belgium', 'Canada', 'Denmark', 'England' ,'France',  'Great Britain', 'Hungary', 'Israel');
my @animals    = ('Alligator', 'Bear',    'Cat',    'Dog',     'Elephant','Fox',     'Goose',         'Horse',   'Iguana');

# 2. Create an array that will contain references
#    to the arrays representing the lines.

my @data = (\@boys, \@girls, \@countries, \@animals);

# 3. We can even go one step further and create
#    a reference to the entire data structure.

my $struct = \@data;

Table of Contents.
Previous | Next.