in reply to how do i read in ANY 2d array
The following operates under the assumption that all rows in your matrix will have equal length (or that you don't care if they don't). Another assumption is that each row of the file corresponds to a row of the matrix. Also, it's expecting comma delimited fields with no embedded (significant) commas. That could be something like a numeric matrix. If you want space delimited with no embedded (significant) space you would change the split to [ split ]
my @matrix; while( <> ) { chomp; push @matrix, [ split /\s*,\s*/, $_ ]; } # Now @matrix is an array of array references.
You asked to make it as short as possible. Using map shortens the construct:
my @matrix = map { chomp; [ split /\s*,\s*/, $_ ] } <>;
That's shortens it while avoiding a negative impact on readability. It does have the disadvantage of slurping the file, but unless your matrix is really big that ought not matter. I don't think you're looking for a golf solution, so it makes sense to stop there, and in fact, recommend the while(){} method instead.
Update: Bah! I should have read that BrowserUk already provided a similar and perfectly good answer. Well, at least now you get two explanations of the same concepts.
Dave
|
|---|