将csv文件中的所有列打印到新文件中的行的Perl脚本

cwdobuhd  于 2023-01-28  发布在  Perl
关注(0)|答案(2)|浏览(159)

我的. 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)在定义数组时出现,因为这不是定义数组的有效方法。有没有其他方法可以做同样的事情。
现在我面临的问题,而内容的每列到一个数组,因为我可以定义多个数组根据需要。

zzzyeukh

zzzyeukh1#

CSV文件中的数据需要转置,根据所显示的所需输出判断

use warnings;
use strict;
use feature 'say';

use Text::CSV;

my $file = shift // die "Usage: $0 file\n";

my $csv = Text::CSV->new ({ binary => 1, auto_diag => 2 });

my @data;
open my $fh, $file or die "Can't open $file: $!";    
while ( my $row = $csv->getline($fh) ) { 
    push @data, $row;
}
close $fh;

# Transpose data
my @res;
foreach my $row (@data) {
    foreach my $col_n (0 .. $#$row) {
        push @{ $res[$col_n] }, $row->[$col_n];
    }
}

# Print results
for my $row (@res) {
    say "@$row";
}

语法$#$name表示该name的数组引用中的最后一个索引。
虽然所显示的数据很容易手动解析†,但最好将任务委托给CSV库,我使用优秀的Text::CSV来读取和解析CSV文件。
结果(转置)数据打印到STDOUT,因此可以重定向到文件。或者更改最后一部分以直接打印到文件。
即使只是

my @data = map { chomp; [ split /\s*,\s*/ ] } <>;

对于一个在命令行中给出名字的文件(在@ARGV中找到,因此可以通过<>逐行读取)。然而,只要文件中有任何更有趣的东西--空格、换行符、引号... --我们就真的需要一个库。所以只要使用库就行了。

8e2ybdfx

8e2ybdfx2#

我简单的回答是:

#!/usr/bin/perl
use warnings; use strict;

my $file = "data.txt";
my $column_separator = ',';
open (my $INFILE, "<" , "$file");

my @rows = ();

my $row=0;
while (<$INFILE>) {

  chomp;
  next if (/^$/);

  my @cols = split(",");

  for(my $c = 0; $c < scalar @cols; $c++) {
    $rows[$c][$row] = "" . $cols[$c];
  }

  $row++;
}

for my $row(@rows) {
  print join(",", @{$row}), "\n";
}

我不是perlMaven,但这似乎很合适(文件处理除外)。

相关问题