的过程中的评论所解释的,冷凝的
my @matrix = map { [ split '', $_ ] } <$fh>;
的金刚石操作者<>
在list context返回的所有行(见I/O operators),从而每个由块中处理的map和返回的列表分配给@matrix
。
在split打破每行($_
)成字符(''
)的块和anonymous array由该列表([...]
)的。给定split
的默认值可以写为map { [ split '' ] }
。
始终使用词法文件句柄,最好这样
my $file = 'gwas.txt';
open my $fh, '<', $file or die "Couldn't open $file: $!";
正如在评论中指出,该处理整个文件分割成一个阵列。为了处理两个文本块,每个文本块放到它自己的数组中,我们可以把它写成一个循环(并用空行来区分块)。
my @matrix;
my $index = 0;
while (<$fh>) {
$matrix[$index++] = [ split '', $_ ];
}
这使得一个匿名数组[ ... ]
与线元件和它的阵列中@matrix
分配给$index
点(并且递增索引)。这样做的另一种方法是
my @row = split '', $_;
$matrix[$index++] = \@row;
其中一个新的数组在每次迭代中被构造并且被赋值给它的引用。
然后我们需要用空行来区分块。我们还需要管理这两个数组,通过在另一个数据结构中引用数组(矩阵)很好地完成了什么,比如说一个数组。
use warnings;
use strict;
use Data::Dump qw(dd);
my $matrices; # will be an arrayref, for references to matrices
my $file = 'matrices.txt';
open my $fh, '<', $file or die "Can't open $file: $!";
my @matrix;
my $index = 0;
while (<$fh>) {
chomp;
if (/^\s*$/) { # blank line, done with one matrix
$index = 0; # reset index
push @$matrices, [ @matrix ]; # store anonymous array for @matrix
}
else {
@matrix[$index] = [ split '', $_ ];
++$index;
}
}
push @$matrices, [ @matrix ]; # the last one in the file
close $fh;
print "Spot check: \$matrices->[0][2][2]: $matrices->[0][2][2]\n";
dd($matrices);
这对数据持有假设,通常它具有确切的预期格式。
请参阅参考资料perlreftut的教程和关于数据结构perldsc的食谱。
另请参阅answer by xxfelixxx,所有这些都以非常不同的方式进行。
还有很多其他的方法可以做到这一点。
这是一个谜题?什么样的计数系统具有带'(2,4)'索引的'K'和带有'(1,0)'的'N'?你可以解释吗?但首先 - 你能告诉我们你做了什么以及你有什么问题吗?预计这里的问题是关于你的code_。 – zdim
@zdim我的错!只是修复这些并添加了代码。 –
这样比较好,谢谢(仍然,我认为你的意思是'a [2] [2] == K' ...?)至于代码:通过让数据结构在每个数据结构中携带_references_来创建多维结构插槽。阅读参考资料:tutorial [perlreftut](http://perldoc.perl.org/perlreftut.html)和一本食谱[perldsc](http://perldoc.perl.org/perldsc.html)。你想要array array,在'pelrdsc' – zdim