arrays - How do I build a 2d matrix using STDIN in Perl? -
How do I create a 2D matrix using STDIN?
If I input a matrix then:
1 2 3 4 5 6 7 5 6 7 8 9 4 5 6 3 3 3
How can I input it and make two matrix out of it?
This is my code so far
while (defined ($ a = & lt; STDIN>)) {Chomp ($ a); Push @ a, ($ A); }
This is just for input
I understand that I can add each line to a stack. When all of the matrix is inserted, then I can take each line, I can break it from space to create an array. Then I need to create an array reference and push this reference into an array to create my matrix. How do i hake Is there an easier way? I am raining on my head for 3 days on this. I'm feeling very stupid ...
Other answers are missing the need to read a Breaking multiple matrices on a blank line, there are a few different ways to go about this, in which frobbling contains $ /
, but here's the one who appeals to me.
# Read the matrix from a handle, divided by the column, whotspace # and delimited by new lines. A matrix ends with a blank line # (which is used) or eof. Sub read_matrix_from {my (handles $) = @_; My @ out; While (& lt; $ handle & gt;) {until all / \ S /; Push @ out, [partition]; } Return \ @out; } My @matrices; Push @matrices, read_matrix_from (\ * ARGV) until eof ();
The last part of the taste Season, of course - you're using clearly opened handles instead of ARGV magic, and you already know how much you read instead Being in the EOF, etc.
Comments
Post a Comment