Search code examples
perlperl-data-structures

How do I use a 2 dimensional array for accessing data in a file using Perl?


I am new to Perl coding & am facing a situation. Here is the problem statement:

I have a file which contains some data (only numbers) in matrix form like

1 2 3 4 5 6 .......
7 9 4 6 7 8 .......
...................
...................

I have another file which contains 2 rows of data (some coordinates) like

30 50
04 09
80 90
.. ..
.. ..

These are the coordinates of data situated in the first file, I want to extract that data from the first file & paste in the 3rd row in the second file, for example in the first case I have to search the element in 30th row & 50th column in the first file & paste it in the 1st row 3rd column of the second file.


Solution

  • This isn't hard.

    First, you will have to parse the value matrix. If the input is in the filehandle $fh, then you could do:

    my @data;
    while(<$fh>) {
      chomp;              # remove newline
      my @row = split;    # split the current line on whitespace
      push @data, \@row;  # put a reference to this row into @data.
    }
    

    Arrays can only contain scalars, so we have to put a reference of the row into our data matrix.

    The above could be written as

    my @data = map { chomp; [split] } <$fh>;
    

    instead; the [...] produces an anonymous arrayref, and map transforms a list by applying the action in the block.

    The data can be accessed like $data[$y][$x]. If you want to swap the indices, this becomes akward in Perl, but isn't impossible.

    To access the data at the coordinates from the second file (I'll assume the filehandle is $fh2), we just split those lines and look up the element:

    while (<$fh2>) {
      chomp;
      my ($x, $y) = split;
      say "at x=$x, y=$y there is $data[$y][$x]";
    }
    

    Be sure to use strict; use warnings; at the top of each script to catch errors. say needs perl 5.10 or later.