Hi,
I want to create a CSV file using Perl and write some data to it. Is there any way to do that?
Thank You
Hi,
I want to create a CSV file using Perl and write some data to it. Is there any way to do that?
Thank You
You could use Class:CSV.
use Class::CSV;
my $csv = Class::CSV->new(
fields => [qw/userid username/]
);
$csv->add_line([2063, 'testuser']);
$csv->add_line({
userid => 2064,
username => 'testuser2'
});
$csv->print();
# 2063,testuser
# 2064,testuser2
Edit: For more libraries, you can search CPAN.
Check out this tutorial for writing to files http://www.comp.leeds.ac.uk/Perl/filehandling.html
We usually use Text::CSV_XS
(which the above-mentioned Class::CSV
is based on)
UPDATE: Commenters below also suggest using Text::CSV
which will load up Text::CSV_XS
or, if that's not avialable, fall back on Text::CSV_PP
that doesn't have XS
dependency and may be easier to install.
There is more than one way to do it.
There are many others on CPAN, too.
Of course, you could ignore all this and just use a loop, a join and a print:
my @table = (
[ 'a', 'b', 'c'],
[ 1, 2, 3 ],
[ 2, 4, 6 ],
);
for my $row ( @table ) {
print join( ',', @$row ), "\n";
}
Just run your script and redirect output to a file, bang! you are done. Or you could get crazy and open a file handle, and print directly to a file.
But then you won't handle multi-line fields, or embedded commas, or any of the many other oddities that can pop up in this sort of data processing task. So be careful with this approach.
My recommendations: