Read text file and convert to Matrix / array of array in Perl

This article about How to crate a  multidimensional array ? and how to read text file and convert to matrix .First we consider an array of array , An array of arrays is a two-dimensional structure that consists in an array whose elements are references to other arrays.Each element of the array (let's call them sub arrays) is also an array, so we use anonymous arrays to define each sub array.
Example Array of array / Matrix
@matrix = (
["one","two","three"],
[4,5,6]
);

To access the 6 in the example:
$element = $matrix[1][2];

Let's assume that you have a file called "info.txt" and every line of this file consists of many words, each one separated by a comma and you want to store the contents of the file in an array of array structure and print all elements .

Perl File(read-matrix.pl)


Text File(info.txt)
Jana,20,10
Mugund,10,10
Kabil,20,10
Achchu,10,10

Output of this code :

Row Size    : 4
Coloum Size : 3
Element [0][0] = Jana
Element [0][1] = 20
Element [0][2] = 10

Element [1][0] = Mugund
Element [1][1] = 10
Element [1][2] = 10

Element [2][0] = Kabil
Element [2][1] = 20
Element [2][2] = 10

Element [3][0] = Achchu
Element [3][1] = 10
Element [3][2] = 10

Post a Comment

Thank you for vising

Previous Post Next Post