Please do not go with the existing
wrong answers. Here is a description of the basic CSV spec as implemented in most Microsoft products:
- Rows are delimited by returns. (\r\n or \n depending on the platform, binmode, etc.)
- Fields within a row are delimited by ",". (When saving in "text" format the separator is often "\t" instead.)
- Fields may be quoted or unquoted.
- Quoted fields are literal text that start and end with an unpaired ". Separators, returns, etc can appear within a quoted field, and " can appear doubled.
- Unquoted fields cannot contain the separator, returns, or quotation marks. They are also subject to some interpretation. For instance numbers may appear in floating point, and an empty field is a null (represented within Perl by undef - very few parsers get this right).
- It is customary for the first row to be the field names, and for all rows to have the same number of fields.
With that in mind, here is a snippet to format a row:
# Takes an array and returns it as a CSV row
sub format_csv {
my @fields = @_;
foreach (@fields) {
if (not defined($_)) {
$_ = "";
}
elsif (0 == length($_)) {
$_ = '""';
}
elsif (/\s|"|'|,/) {
s/"/""/g;
$_ = qq("$_");
}
}
(join ",", @fields) . "\n";
}
With that function, supposing that $file was a file you wanted to write, @cols an array of columns that you wanted to put in a CSV file, and @data was an array of hash references with your data (see
References Quick Reference if you don't know what an array of hash references is), you could write it as follows:
local *FILE;
open (FILE, "> $file") or die "Cannot write '$file': $!";
print FILE format_csv(@cols);
foreach my $row (@data) {
print FILE format_csv(@$row{@cols});
}
close(FILE) or die "Cannot close '$file': $!";
Note that I have put in error checking as very wisely recommended in
perlstyle...
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.