How to save a perl output as csv file?

时间:2018-07-24 10:13:07

标签: perl file csv

I wrote a perl script that at the moment outputs my results on screen by using printf function. In particular I would like to, for each printed row ,save it in a csv file. To print my results I'm using :

printf "%-3.2f" %-3.2f ", $myVar1, $myVar2 if $myVar3;
printf "%-3.2f", $myVar4;

So it depends on $myVar3 if true or false I'll get from 2 to 3 columns of values.

As I said, I would like to save this output as csv file at the same time, but I don't know how to proceed. Thanks.

UPDATE
I was able to save my runtime output into a csv a file, but at the end of the script I get the following message in the standard error output:

Can't use an undefined value as a symbol reference at .....line 296

that line is :

close my $fh or die "failed to close my output.csv: $!";

I checked into the generated csv file and I can find all my data in, but I wonder why I'm getting this error ...

Below part of my code to create a csv object:

use Text::CSV;
.....other code.....
my $csv = Text::CSV->new({binary => 1, eol => $/ }) or die "Failed to create a CSV handle: $!";
my $filename = "output.csv";
open my $fh, ">:encoding(utf8)", $filename or die "failed to create $filename:$!";
.....inside my while loop I save my runtime data at each iteration....
$csv->print($fh,[$myVar1,$myVar2]) if $myVar3;
$csv->print($fh, [$myVar4,$myVar5]);
......at the exit of the while loop close my csv file....
close my $fh or die "failed to close my output.csv: $!";

In that latest line code that I'm getting the above message. Why?

0 个答案:

没有答案