Broad Network


Perl Two-Dimensional Array

Perl Multi-Dimensional Array- Part 1

Foreword: In this part of the series we look at a simple way to create and use a two dimensional array in Perl.

By: Chrysanthus Date Published: 2 Dec 2012

Introduction

This is part 1 of my series, Perl Multi-Dimensional Array. In this part of the series we look at a simple way to create and use a two dimensional array in Perl. This is a tutorial.

The code samples of this series are of ActivePerl. If you are using traditional Perl, then begin each code sample with something like, #!/usr/bin/perl .

Pre-Knowledge
This series is part of the volume, Perl Course. At the bottom of this page, you will find links to the different series you should have read before coming here.

Need for a Two-Dimensional Array
You need a two dimensional array when you want to keep information of tabular (table) form. The following table has a list of products of a supermarket; the column headings are, ProductID Product Name, Category, Number, Cost Price and Selling Price

ProductID, ProductName, Category, Number, CostPrice, SellingPrice
1, TV Set, Entertainment, 50, 25, 30
2, DVD, Entertainment, 50, 20, 25
3, Clothe Box, Household, 45, 16, 21
4, Perfume, Beauty, 100, 2, 3
5, Banana, Fruit, 125, 5, 7
6, Pear, Fruit, 135, 3, 4

We shall see how to create a two-dimension array that will hold all these data in Perl.

Indexing in Perl Two-Dimensional Array
A two-dimensional array has rows and columns. Counting of rows begins from zero. Counting of columns also begins from zero. In Perl Two-Dimensional Array, you quote the row position (index) first before you quote the column position. So the value of [0][0] in the above table is, ProductID. This means the row concerned is row zero and the column concerned is column zero. The value of [1][0] in the above table is, 1. The value of [0][1] in the above table is, ProductName. The value of [2][1] is, DVD; and so on.

Creating a Two-Dimensional Array
You create an empty two-dimensional array in the same way that you create an empty one-dimensional array. Let the name of our two dimensional array be arr. So you would create the empty two-dimensional array as follows:

    my @arr;

Accessing an Array Element
You access an element in a two dimensional array with the following syntax:

    $arrayName[rowIndex][columnIndex]

We shall see examples below

Placing Elements into a 2D Array One-by-One
You can place elements into a two-dimensional array one-by-one. You do this using the square brackets and the corresponding indices (row and column numbers). The following code places the first and second rows of the above table into the array, one element at a time:

use strict;

    my @arr;

    $arr[0][0] = "ProductID";
    $arr[0][1] = "ProductName";
    $arr[0][2] = "Category";
    $arr[0][3] = "Number";
    $arr[0][4] = "CostPrice";
    $arr[0][5] = "SellingPrice";
    $arr[1][0] = 1;
    $arr[1][1] = "TV Set";
    $arr[1][2] = "Entertainment";
    $arr[1][3] = 50;
    $arr[1][4] = 25;
    $arr[1][5] = 30;

Note: You can replace a value in a cell in the same way that you assign value for the first time. Also note the quotes used with strings above.

Reading Values from a 2D Array One-by-One
The syntax to read a value from a two-dimensional array into a variable is:

    $var = $arrayName[rowIndex][columnIndex];

So you read a value in a similar way that you place a value. The following code would place the first two rows of the above table into an array and then print them out from the array.

use strict;

    my @arr;

    $arr[0][0] = "ProductID";
    $arr[0][1] = "ProductName";
    $arr[0][2] = "Category";
    $arr[0][3] = "Number";
    $arr[0][4] = "CostPrice";
    $arr[0][5] = "SellingPrice";
    $arr[1][0] = 1;
    $arr[1][1] = "TV Set";
    $arr[1][2] = "Entertainment";
    $arr[1][3] = 50;
    $arr[1][4] = 25;
    $arr[1][5] = 30;


    for (my $i=0; $i<2; ++$i)
        {
            for (my $j=0; $j<6; ++$j)
                {
                    print $arr[$i][$j] . ", ";
                }
            print "\n";        
        }

Read and try the code. In a commercial program you would have to modify the code to remove the last comma displayed at the end of a row.

Placing Elements into a 2D Array Row-by-Row
You can place elements into a 2D array one row at a time. The syntax to place a row into a 2D array is:

    $arrayName[rowIndex] = [value1, value2, value3, …];

Note that the values of the row are in square brackets and not arc brackets. The following program places all the rows of the above table into a 2D array and then displays them.

use strict;

    my @arr;

    $arr[0] = ["ProductID", "ProductName", "Category", "Number", "CostPrice", "SellingPrice"];
    $arr[1] = [1, "TV Set", "Entertainment", 50, 25, 30];
    $arr[2] = [2, "DVD", "Entertainment", 50, 20, 25];
    $arr[3] = [3, "Clothe Box", "Household", 45, 16, 21];
    $arr[4] = [4, "Perfume", "Beauty", 100, 2, 3];
    $arr[5] = [5, "Banana", "Fruit", 125, 5, 7];
    $arr[6] = [6, "Pear", "Fruit", 135, 3, 4];

    for (my $i=0; $i<7; ++$i)
        {
            for (my $j=0; $j<5; ++$j)
                {
                    print $arr[$i][$j] . ", ";
                }
            print $arr[$i][5] . "\n";        
        }

Note that the string values are in quotes. Read and try the code.

Irregular Nature of a 2D Array
The above 2D array is regular in the sense that the edges of the array are straight. This means that you have equal number of columns (cells) for each row and equal number of rows (cells) for each column. In other words all the rows have elements for each cell and all the columns have elements for each cell. For the above array in the code, there are 6 cells per row and 7 cells per column; no cell is undefined.

It is possible to have a 2D array in Perl that is irregular. For a 2D Perl array, you do not have to place a new element (value) in the next “available” cell. The following code illustrates this:

    my @arr;

    $arr[0][0] = "00";
    $arr[0][2] = "02";
    $arr[1][3] = "13";
    $arr[2][1] = "21";

This code would be executed. The array is irregular. This array would have been a 3-row-by-4-column array, judging from the maximum row and maximum column numbers. There are many cells, which are undefined (empty) for this array, e.g. cell [0][1].

2D Array by Initialization
If you try to learn Perl from the specification (or manual) you would probably find the learning process difficult. Specifications or manuals are written for experts. A teacher like me has to read the specification and then present the knowledge in learnable form. That, I believe is what I have done for this Perl Professional Course (link below), which I assume you are going through. I intend to do the same for the Perl Advanced Course.

Back to 2D array: “Array by Initialization” is a phrase I have borrowed from C++. It means creating an array where the left hand operand to the assignment operator is a variable and the right hand operand is the content (value) of the array. The content is within special symbols.

With Perl, for the 2D initialization array, you have the variable, this time with the scalar symbol, $ and not the array symbol, @. Note, we are creating a 2D array by initialization and not by the normal way; so there is a difference. So you would have something like,

    my $twoDArrRef;

for the array declaration, where twoDArrRef is the array name. $twoDArrRef is actually a reference but do not worry about that in this series.

The right hand operand begins with [ and ends with ] immediately followed by “;”. Inside the square brackets pair, you have rows. Each row is a one-dimensional array. Each 1D row is delimited by square brackets pair. The 1D rows are separated by commas (,) and not semicolons (;). Within each 1D array, the items are separated by commas. There is no comma after the last item in a 1D row and no comma after the last 1D row. Read and try the following example that illustrates this:

use strict;

    my $twoDArrRef;

    $twoDArrRef = [
                     ["ProductID", "ProductName", "Category", "Number", "CostPrice", "SellingPrice"],
                     [1, "TV Set", "Entertainment", 50, 25, 30],
                     [2, "DVD", "Entertainment", 50, 20, 25],
                     [3, "Clothe Box", "Household", 45, 16, 21],
                     [4, "Perfume", "Beauty", 100, 2, 3],
                     [5, "Banana", "Fruit", 125, 5, 7],
                     [6, "Pear", "Fruit", 135, 3, 4]
                 ];

    print $$twoDArrRef[2][1];

To access an element, you type the variable name preceded by two consecutive $ symbols. You use two square brackets as expected.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

If you like this article, plus it by clicking:

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
More Related Links
PurePerl MySQL API
Web Development Course
Major in Website Design
Producing a Pure Perl Library

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message