madhavb has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

I have flat file in unix as shown...

11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

I have to read this in to a 2D array and access i,j th element
i.e should be able to print each element in a loop.
Please help me in achieving the above task.

Thanks for any help.
a new monk

Replies are listed 'Best First'.
Re: Flat file in an array.
by chromatic (Archbishop) on Apr 22, 2008 at 18:20 UTC

    Which part of the process is giving you trouble? You need to open a file, probably loop over the readline operator with a while loop, and likely split on whitespace into an array. Eventually you need to print the results.

Re: Flat file in an array.
by pc88mxer (Vicar) on Apr 22, 2008 at 19:12 UTC
    Storing and accessing stuff in a 2d array can get a little hairy syntactically. Here's some example code:
    my $list = []; # let's start with an array ref while (<>) { chomp; push(@$list, [split(' ', $_)]); # note the array ref [] constructor } # access the i-j-th element: print "list[2][3] = ", $list->[2]->[3], "\n"; # access by rows: for my $i (0..$#$list) { print "number of elements in row $i: ", scalar(@{$list->[$i]}), "\n" +; print "last index of row $i = ", $#{$list->[$i]}, "\n"; } # access each element: for my $i (0..$#$list) { for my $j (0.. $#{$list->[$i]}) { print "list[$i][$j] = ", $list->[$i]->[$j], "\n"; } }
    If you are doing a lot of matrix operations on your 2D-arrays, you might look into PDL as an alternative.
Re: Flat file in an array.
by MidLifeXis (Monsignor) on Apr 23, 2008 at 16:44 UTC

    Would this be homework? If so, please say so. We are not against helping, but we will not spoon feed you. Also, please include what you have tried, errors you are seeing, and anything else that may help us help you.

    Also see How do I post a question effectively?.

    --MidLifeXis