[sf-perl] writing a csv file: how do i embed a newline in a cell?

Joseph Brenner doom at kzsu.stanford.edu
Sun Apr 10 13:33:48 PDT 2011


George Hartzell <hartzell at alerce.com> wrote:
> David Alban writes:
>  > greetings,
>  >
>  > i'm writing a program that will produce a csv file so that folks can
>  > import the output into an ms excel spreadsheet. [...]
>
> If you really want a CSV file, then I'd try to let someone else do the
> work and use Text::CSV_XS.  Pay attention to the pod about embedded
> newlines and quoting and it should work (though I admit I haven't
> tried it).

Yes, if you're working with csv files and perl, you really should be
using Text::CSV_XS
(or DBD::CSV, which uses it internally).   Trying to hack CSV with
home grown code
is usually a mistake.

If the "binary" option is not the default yet, don't forget to turn it
on: that should allow you to put newlines inside a string.  It at
least used to be necessary to use "binary" to get it to deal with the
full range of latin-1 correctly.

Looks like I called that right:
http://search.cpan.org/~hmbrand/Text-CSV_XS-0.81/CSV_XS.pm#Embedded_newlines

Paul Makepeace has a point about the general nastiness of csv format.
It's a "standard" without a standard, it *looks* simple but has a lot
of funny edge cases to it, and there's no guarantee that a csv file
that's read correctly by one app will be read correctly by another.


More information about the SanFrancisco-pm mailing list