Saturday, May 17, 2014

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

Posted By: Achchuthan Yogarajah - 5/17/2014 01:05:00 AM

Share

& Comment

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

About Achchuthan Yogarajah

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Believe in Yourself - Achchuthan Yogarajah ACHCHUTHAN.ORG. Designed by Templateism .