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


In reply to Re: how do i read in ANY 2d array by davido
in thread how do i read in ANY 2d array by DanielM0412

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.