Loading data from a file into a 2d array

I am just starting out with perl and would like to help with arrays, please. I am reading the lines from the data file and breaking the line into fields:

open (INFILE, $infile);
do {
my $linedata = <INFILE>;
my @data= split ',',$linedata;
....
} until eof;

Then I want to save the individual field values ​​(in @data) in and array so that the array looks like an input data file, i.e. the first "row" of the array contains the first row of data from INFILE, etc.

Each row of data from infile contains 4 values, x, y, z and w, and as soon as the data is all in the array, I have to transfer the array to another program that reads x, y, z, w and displays the value of w on the screen at a point defined by the value of x, y, z. I cannot transfer data to another program in stages, since the program expects the data to be in 2d matrtix format. Any help is greatly appreciated. Chris

+3
source share
1 answer

This is not so difficult, you just need to store the splits, not in their separate list, but in the array, occupying the slot of a larger array:

my @all_data;

while (my $linedata = <INFILE>) { 
   push # creates the next (n) slot(s) in an array
       @all_data
     , [ split ',',$linedata ] 
       # ^ we're pushing an *array* not just additional elements.
      ; 
}

However, if you are just trying to read a well-known concept as a format for comma-separated values, then look at something like Text::CSV, since the full capabilities of CSV are more than comma-separated.

+6
source

Source: https://habr.com/ru/post/1743668/


All Articles