Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Text::CSV to print a line on a csv files based on variables content

Tags:

perl

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.

like image 976
BlueStarry Avatar asked Dec 06 '22 19:12

BlueStarry


2 Answers

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.

like image 133
Jonathan Leffler Avatar answered Dec 08 '22 09:12

Jonathan Leffler


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]);
like image 38
Jeff Kubina Avatar answered Dec 08 '22 09:12

Jeff Kubina