Output to a csv file using Text::CSV_XS
I have a perl script which works fine printing to the screen but when I
try to redirect the output to a csv file I get the following error -
Expected fields to an array ref. I am using Text::CSV_XS and the line that
gives the error is - $csv->print ($fh, $_) for @rows;
#!/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 });
# Either successfully open the file or else die (stop the program)
open(INPUT, $file) or die("Input file $file not found.\n");
# Read each line from the file, one line at a time.
while(my $line = <INPUT>)
{
if($line =~ /Assay/)
{
@words = split(" ",$line);
push @rows, $words[1];
# print "$words[1],\n";
}
if($line =~/Date/)
{
@words = split(" ",$line);
push @rows, $words[1];
push @rows, $words[2];
# print "$words[1],\n";
# print "$words[2],\n";
}
if($line =~/Patient/)
{
@words = split(" ",$line);
push @rows, $words[0];
push @rows, $words[1];
push @rows, $words[2];
# print "$words[0] $words[1]$words[2],\n";
}
if($line =~/channel_index/)
{
print $line;
}
if($line =~/Channel/)
{
@words = split(" ",$line);
push @rows, $words[1];
push @rows, $words[2];
# print "$words[1],$words[2],\n";
}
if($line =~/DCMean/)
{
@words = split(" ",$line);
push @rows, $words[0];
push @rows, $words[1];
# print "$words[0],$words[1]\n";
}
}
$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();
No comments:
Post a Comment