我的. csv文件看起来像:
sim_time,a,b,c,d
0,0,0,0,0
12,0,1,1,0
115,1,1,1,1
200,0,0,1,0
我有多个csv文件,其中没有行和列是不同的。
输出应如下所示:
sim_time 0 12 115 200
a 0 0 1 0
b 0 1 1 0
c 0 1 1 1
d 0 0 1 0
我尝试使用的代码如下:
#!/usr/bin/perl
my $file = "report_69.csv";
my $column_separator = ',';
open (my $INFILE, "<" , "$file");
open(my $FILE,">","report_69.txt") or die "$!";
while (<$INFILE>) {
chomp;
my @c = split(',', $_);
my $d = @c;
print $d;
my @columns = split(/$column_separator/);
for( $a = 0; $a < $d; $a = $a + 1 ) {
push ("@x_{$a}", $columns[$a] ); # the problem (1)
}
}
问题(1)在定义数组时出现,因为这不是定义数组的有效方法。有没有其他方法可以做同样的事情。
现在我面临的问题,而内容的每列到一个数组,因为我可以定义多个数组根据需要。
2条答案
按热度按时间zzzyeukh1#
CSV文件中的数据需要转置,根据所显示的所需输出判断
语法
$#$name
表示该name
的数组引用中的最后一个索引。虽然所显示的数据很容易手动解析†,但最好将任务委托给CSV库,我使用优秀的Text::CSV来读取和解析CSV文件。
结果(转置)数据打印到
STDOUT
,因此可以重定向到文件。或者更改最后一部分以直接打印到文件。即使只是
对于一个在命令行中给出名字的文件(在
@ARGV
中找到,因此可以通过<>
逐行读取)。然而,只要文件中有任何更有趣的东西--空格、换行符、引号... --我们就真的需要一个库。所以只要使用库就行了。8e2ybdfx2#
我简单的回答是:
我不是perlMaven,但这似乎很合适(文件处理除外)。