My script is fairly large but I'll simplify the code here. Suppose that I create a CSV and I write the header like this:
my $csv = Text::CSV->new ({binary => 1}, eol => "\n");
open(my $out, ">", "$dir/out.csv") or die $!; #create
$out->print("CodeA,CodeB,Name,Count,Pos,Orientation\n"); #I write the header
Suppose that I got the some values stored in different variables and I want to write those variables as a line in the CSV. I cannot figure out how, because on the Text::CSV documentation the print is not clearly explained, there's no direct examples and i don't know what an array ref is.
Here's a trivial example of using Text::CSV to write a CSV file. It generates a header line and a data line, and does so from fixed data.
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;
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: $!";
my(@heading) = ("CodeA", "CodeB", "Name", "Count", "Pos", "Orientation");
$csv->print($fh, \@heading); # Array ref!
my(@datarow) = ("A", "B", "Abelone", 3, "(6,9)", "NW");
$csv->print($fh, \@datarow); # Array ref!
close $fh or die "failed to close $filename: $!";
The row of data is collected in an array — I used @heading
and @datarow
. If I was outputting several rows, each row could be collected or created in @datarow
and then output. The first argument to $csv->print
should be the I/O handle — here, $fh
, a file handle for the output file. The second should be an array ref. Using \@arrayname
is one way of creating an array ref; the input routines for the Text::CSV module also create and return array refs.
Note the difference between the notation used here in the Text::CSV->new
call and the notation used in your example. Also note that your $out->print("…");
call is using the basic file I/O and nothing to do with Text::CSV. Contrast with $csv->print($fh, …)
.
The rest of the code is more or less boilerplate.
output.csv
CodeA,CodeB,Name,Count,Pos,Orientation
A,B,Abelone,3,"(6,9)",NW
Note that the value with an embedded comma was surrounded by quotes by the Text::CSV module. The other values did not need quotes so they did not get them. You can tweak the details of the CSV output format with the options to Text::CSV->new
.
For the headers you can use
$status = $csv->print ($out,[qw(CodeA CodeB Name Count Pos Orientation)]);
and for a row of values use
$status = $csv->print ($out,[$valueA,$valueB,$valueName,$valueCount,$valuePos,$valueOrientation]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With