我有一個perl腳本,它可以很好地打印到屏幕上,但是當我嘗試將輸出重定向到csv文件時,出現以下錯誤:Expected fields to an array ref
。我使用Text::CSV_XS
,並且給出了錯誤的行是$csv->print ($fh, $_) for @rows;
使用Text :: CSV_XS輸出到csv文件
#!/user/local/bin/perl
use Text::CSV_XS;
$|=1;
sub main {
print "Enter file to process: ";
my $file = <STDIN>;
chomp $file;
my @rows;
my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
open(INPUT, $file) or die("Input file $file not found.\n");
while(my $line = <INPUT>) {
if($line =~ /Assay/) {
@words = split(" ",$line);
push @rows, $words[1];
}
if($line =~/Date/) {
@words = split(" ",$line);
push @rows, $words[1];
push @rows, $words[2];
}
if($line =~/Patient/) {
@words = split(" ",$line);
push @rows, $words[0];
push @rows, $words[1];
push @rows, $words[2];
}
if($line =~/channel_index/) {
print $line;
}
if($line =~/Channel/) {
@words = split(" ",$line);
push @rows, $words[1];
push @rows, $words[2];
}
if($line =~/DCMean/) {
@words = split(" ",$line);
push @rows, $words[0];
push @rows, $words[1];
}
}
$csv->eol ("\r\n");
open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
$csv->print ($fh, $_) for @rows;
close $fh or die "new.csv: $!";
close(INPUT);
}
main();
這工作完美。謝謝! – Craig