如何构建在Perl使用STDIN一个二维矩阵? [英] How do I build a 2d matrix using STDIN in Perl?
问题描述
我如何使用STDIN建立一个二维矩阵?
How do I build a 2d matrix using STDIN?
如果我输入像这样一个矩阵:
If I input a matrix like so:
1 2 3
4 5 6
7 5 6
7 8 9
4 5 6
3 3 3
我怎么输入这个并创建两个矩阵出这个?
how do I input this and create two matrices out of this?
下面是我的code到目前为止
Here's my code so far
while (defined ($a=<STDIN>)) {
chomp ($a);
push @a,($a);
}
这仅仅是输入。
我的理解是,我可以每行只添加到堆栈。当矩阵都放在我可以把每一行,通过空间打破创建一个数组。然后,我需要创建一个数组引用,推动此引用到一个数组创建我的矩阵。如何赫克我做到这一点?是否有更简单的方法?我一直在抨击我的头在这3天。我觉得pretty该死的愚蠢现在...
My understanding is I can just add each row to a stack. When the matrices are all put in I can take each line, break by space to create an array. I then need to create an array reference and push this reference into an array to create my matrix. How the heck do I do this? Is there an easier way? I've been bashing my head on this for 3 days now. I feel pretty damn stupid right now...
推荐答案
其他的答案似乎缺少要求从同一输入读取多个矩阵,打破一个空行。有几种不同的方式去了解这一点,包括frobbing $ /
,但这里有一个吸引我的。
The other answers seem to be missing the requirement to read multiple matrices from the same input, breaking on a blank line. There are a few different ways to go about this, including frobbing $/
, but here's one that appeals to me.
# Read a matrix from a handle, with columns delimited by whitespace
# and rows delimited by newlines. A matrix ends at a blank line
# (which is consumed) or EOF.
sub read_matrix_from {
my ($handle) = @_;
my @out;
while (<$handle>) {
last unless /\S/;
push @out, [ split ];
}
return \@out;
}
my @matrices;
push @matrices, read_matrix_from(\*ARGV) until eof();
赛季的最后一部分的味道,当然 - 你可能会使用一个明确打开处理,而不是神奇ARGV,你可能提前知道有多少事情你正在阅读,而不是去EOF等
Season the last part to taste, of course -- you might be using an explicitly opened handle instead of ARGV magic, and you might know in advance how many things you're reading instead of going to EOF, etc.
这篇关于如何构建在Perl使用STDIN一个二维矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!