H.Merijn Brand > Text-CSV_XS-1.09 > Text::CSV_XS

Download:
Text-CSV_XS-1.09.tgz

Dependencies

Annotate this POD

Related Modules

Text::CSV
DBD::CSV
Text::xSV
Data::Dumper
IO::File
SQL::Statement
Text::ParseWords
Win32::OLE
DBD::AnyData
Tie::File
more...
By perlmonks.org

CPAN RT

Open  0
View/Report Bugs
Module Version: 1.09   Source  

NAME ^

Text::CSV_XS - comma-separated values manipulation routines

SYNOPSIS ^

 # Functional interface
 use Text::CSV_XS qw( csv );
 # Read whole file in memory as array of arrays
 my $aoa = csv (in => "data.csv");
 # Write array of arrays as csv file
 csv (in => $aoa, out => "file.csv", sep_char=> ";");

 # Object interface
 use Text::CSV_XS;

 my @rows;
 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
 open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!";
 while (my $row = $csv->getline ($fh)) {
     $row->[2] =~ m/pattern/ or next; # 3rd field should match
     push @rows, $row;
     }
 close $fh;

 $csv->eol ("\r\n");
 open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
 $csv->print ($fh, $_) for @rows;
 close $fh or die "new.csv: $!";

DESCRIPTION ^

Text::CSV_XS provides facilities for the composition and decomposition of comma-separated values. An instance of the Text::CSV_XS class will combine fields into a CSV string and parse a CSV string into fields.

The module accepts either strings or files as input and support the use of user-specified characters for delimiters, separators, and escapes.

Embedded newlines

Important Note: The default behavior is to accept only ASCII characters in the range from 0x20 (space) to 0x7E (tilde). This means that the fields can not contain newlines. If your data contains newlines embedded in fields, or characters above 0x7E (tilde), or binary data, you must set binary => 1 in the call to "new". To cover the widest range of parsing options, you will always want to set binary.

But you still have the problem that you have to pass a correct line to the "parse" method, which is more complicated from the usual point of usage:

 my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ });
 while (<>) {           #  WRONG!
     $csv->parse ($_);
     my @fields = $csv->fields ();
     }

this will break, as the while might read broken lines: it does not care about the quoting. If you need to support embedded newlines, the way to go is to not pass eol in the parser (it accepts \n, \r, and \r\n by default) and then

 my $csv = Text::CSV_XS->new ({ binary => 1 });
 open my $io, "<", $file or die "$file: $!";
 while (my $row = $csv->getline ($io)) {
     my @fields = @$row;
     }

The old(er) way of using global file handles is still supported

 while (my $row = $csv->getline (*ARGV)) { ... }

Unicode

Unicode is only tested to work with perl-5.8.2 and up.

On parsing (both for "getline" and "parse"), if the source is marked being UTF8, then all fields that are marked binary will also be marked UTF8.

For complete control over encoding, please use Text::CSV::Encoded:

 use Text::CSV::Encoded;
 my $csv = Text::CSV::Encoded->new ({
     encoding_in  => "iso-8859-1", # the encoding comes into   Perl
     encoding_out => "cp1252",     # the encoding comes out of Perl
     });

 $csv = Text::CSV::Encoded->new ({ encoding  => "utf8" });
 # combine () and print () accept *literally* utf8 encoded data
 # parse () and getline () return *literally* utf8 encoded data

 $csv = Text::CSV::Encoded->new ({ encoding  => undef }); # default
 # combine () and print () accept UTF8 marked data
 # parse () and getline () return UTF8 marked data

On combining ("print" and "combine"): if any of the combining fields was marked UTF8, the resulting string will be marked as UTF8. Note however that all fields before the first field marked UTF8 and contained 8-bit characters that were not upgraded to UTF8, these will be bytes in the resulting string too, possibly causing unexpected errors. If you pass data of different encoding, or you don't know if there is different encoding, force it to be upgraded before you pass them on:

 $csv->print ($fh, [ map { utf8::upgrade (my $x = $_); $x } @data ]);

SPECIFICATION ^

While no formal specification for CSV exists, RFC 4180 1) describes the common format and establishes text/csv as the MIME type registered with the IANA. RFC 7111 2 adds fragments to CSV.

Many informal documents exist that describe the CSV format. "How To: The Comma Separated Value (CSV) File Format" 3) provides an overview of the CSV format in the most widely used applications and explains how it can best be used and supported.

 1) http://tools.ietf.org/html/rfc4180
 2) http://tools.ietf.org/html/rfc7111
 3) http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm

The basic rules are as follows:

CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes. However, if a line contains a single entry that is the empty string, it may be enclosed in double quotes. If a field's value contains a double quote character it is escaped by placing another double quote character next to it. The CSV file format does not require a specific character encoding, byte order, or line terminator format.

Though this is the most clear and restrictive definition, Text::CSV_XS is way more liberal than this, and allows extension:

METHODS ^

version

(Class method) Returns the current module version.

new

(Class method) Returns a new instance of class Text::CSV_XS. The attributes are described by the (optional) hash ref \%attr.

 my $csv = Text::CSV_XS->new ({ attributes ... });

The following attributes are available:

eol

The end-of-line string to add to rows for "print" or the record separator for "getline".

When not passed in a parser instance, the default behavior is to accept \n, \r, and \r\n, so it is probably safer to not specify eol at all. Passing undef or the empty string behave the same.

When not passed in a generating instance, records are not terminated at all, so it is probably wise to pass something you expect. A safe choice for eol on output is either $/ or \r\n.

Common values for eol are "\012" (\n or Line Feed), "\015\012" (\r\n or Carriage Return, Line Feed), and "\015" (\r or Carriage Return). The eol attribute cannot exceed 7 (ASCII) characters.

If both $/ and "eol" in eol equal "\015", parsing lines that end on only a Carriage Return without Line Feed, will be "parse"d correct.

sep_char

The char used to separate fields, by default a comma. (,). Limited to a single-byte character, usually in the range from 0x20 (space) to 0x7E (tilde).

The separation character can not be equal to the quote character or to the escape character.

See also "CAVEATS"

allow_whitespace

When this option is set to true, the whitespace (TAB's and SPACE's) surrounding the separation character is removed when parsing. If either TAB or SPACE is one of the three characters sep_char, quote_char, or escape_char it will not be considered whitespace.

Now lines like:

 1 , "foo" , bar , 3 , zapp

are parsed as valid CSV, even though it violates the CSV specs.

Note that all whitespace is stripped from both start and end of each field. That would make it more than a feature to enable parsing bad CSV lines, as

 1,   2.0,  3,   ape  , monkey

will now be parsed as

 ("1", "2.0", "3", "ape", "monkey")

even if the original line was perfectly acceptable CSV.

blank_is_undef

Under normal circumstances, CSV data makes no distinction between quoted- and unquoted empty fields. These both end up in an empty string field once read, thus

 1,"",," ",2

is read as

 ("1", "", "", " ", "2")

When writing CSV files with always_quote set, the unquoted empty field is the result of an undefined value. To enable this distinction when reading CSV data, the blank_is_undef attribute will cause unquoted empty fields to be set to undef, causing the above to be parsed as

 ("1", "", undef, " ", "2")
empty_is_undef

Going one step further than blank_is_undef, this attribute converts all empty fields to undef, so

 1,"",," ",2

is read as

 (1, undef, undef, " ", 2)

Note that this effects only fields that are originally empty, not fields that are empty after stripping allowed whitespace. YMMV.

quote_char

The character to quote fields containing blanks or binary data, by default the double quote character ("). A value of undef suppresses quote chars (for simple cases only). Limited to a single-byte character, usually in the range from 0x20 (space) to 0x7E (tilde).

quote_char can not be equal to sep_char.

allow_loose_quotes

By default, parsing unquoted fields containing quote_char characters like

 1,foo "bar" baz,42

would result in parse error 2034. Though it is still bad practice to allow this format, we cannot help the fact that some vendors make their applications spit out lines styled this way.

If there is really bad CSV data, like

 1,"foo "bar" baz",42

or

 1,""foo bar baz"",42

there is a way to get this data-line parsed and leave the quotes inside the quoted field as-is. This can be achieved by setting allow_loose_quotes AND making sure that the escape_char is not equal to quote_char.

escape_char

The character to escape certain characters inside quoted fields. This is limited to a single-byte character, usually in the range from 0x20 (space) to 0x7E (tilde).

The escape_char defaults to being the double-quote mark ("). In other words the same as the default quote_char. This means that doubling the quote mark in a field escapes it:

 "foo","bar","Escape ""quote mark"" with two ""quote marks""","baz"

If you change the quote_char without changing the escape_char, the escape_char will still be the double-quote ("). If instead you want to escape the quote_char by doubling it you will need to also change the escape_char to be the same as what you have changed the quote_char to.

The escape character can not be equal to the separation character.

allow_loose_escapes

Parsing fields that have escape_char characters that escape characters that do not need to be escaped, like:

 my $csv = Text::CSV_XS->new ({ escape_char => "\\" });
 $csv->parse (qq{1,"my bar\'s",baz,42});

would result in parse error 2025. Though it is bad practice to allow this format, this attribute enables you to treat all escape character sequences equal.

allow_unquoted_escape

A backward compatibility issue where escape_char differs from quote_char prevents escape_char to be in the first position of a field. If quote_char is equal to the default " and escape_char is set to \, this would be illegal:

 1,\0,2

Setting this attribute to 1 might help to overcome issues with backward compatibility and allow this style.

binary

If this attribute is 1, you may use binary characters in quoted fields, including line feeds, carriage returns and NULL bytes. (The latter could be escaped as "0.) By default this feature is off.

If a string is marked UTF8, binary will be turned on automatically when binary characters other than CR and NL are encountered. Note that a simple string like "\x{00a0}" might still be binary, but not marked UTF8, so setting { binary => 1 } is still a wise option.

decode_utf8

This attributes defaults to TRUE.

While parsing, fields that are valid UTF-8, are automatically set to be UTF-8, so that

  $csv->parse ("\xC4\xA8\n");

results in

  PV("\304\250"\0) [UTF8 "\x{128}"]

Sometimes it might not be a desired action. To prevent those upgrades, set this attribute to false, and the result will be

  PV("\304\250"\0)
types

A set of column types; the attribute is immediately passed to the "types" method.

always_quote

By default the generated fields are quoted only if they need to be. For example, if they contain the separator character. If you set this attribute to 1 then all defined fields will be quoted. (undef fields are not quoted, see "blank_is_undef"). This makes it quite often easier to handle exported data in external applications. (Poor creatures who are better to use Text::CSV_XS. :)

quote_space

By default, a space in a field would trigger quotation. As no rule exists this to be forced in CSV, nor any for the opposite, the default is true for safety. You can exclude the space from this trigger by setting this attribute to 0.

quote_null

By default, a NULL byte in a field would be escaped. This option enables you to treat the NULL byte as a simple binary character in binary mode (the { binary => 1 } is set). The default is true. You can prevent NULL escapes by setting this attribute to 0.

quote_binary

By default, all "unsafe" bytes inside a string cause the combined field to be quoted. By setting this attribute to 0, you can disable that trigger for bytes >= 0x7F.

keep_meta_info

By default, the parsing of input records is as simple and fast as possible. However, some parsing information - like quotation of the original field - is lost in that process. Setting this flag to true enables retrieving that information after parsing with the methods "meta_info", "is_quoted", and "is_binary" described below. Default is false for performance.

verbatim

This is a quite controversial attribute to set, but makes some hard things possible.

The rationale behind this attribute is to tell the parser that the normally special characters newline (NL) and Carriage Return (CR) will not be special when this flag is set, and be dealt with as being ordinary binary characters. This will ease working with data with embedded newlines.

When verbatim is used with "getline", "getline" auto-chomp's every line.

Imagine a file format like

 M^^Hans^Janssen^Klas 2\n2A^Ja^11-06-2007#\r\n

where, the line ending is a very specific "#\r\n", and the sep_char is a ^ (caret). None of the fields is quoted, but embedded binary data is likely to be present. With the specific line ending, this should not be too hard to detect.

By default, Text::CSV_XS' parse function is instructed to only know about "\n" and "\r" to be legal line endings, and so has to deal with the embedded newline as a real end-of-line, so it can scan the next line if binary is true, and the newline is inside a quoted field. With this option, we tell "parse" to parse the line as if "\n" is just nothing more than a binary character.

For "parse" this means that the parser has no more idea about line ending and "getline" chomps line endings on reading.

auto_diag

Set this attribute to a number between 1 and 9 causes "error_diag" to be automatically called in void context upon errors.

In case of error 2012 - EOF, this call will be void.

If auto_diag is set to a numeric value greater than 1, it will die on errors instead of warn. If set to anything unrecognized, it will be silently ignored.

Future extensions to this feature will include more reliable auto-detection of autodie being active in the scope of which the error occurred which will increment the value of auto_diag with 1 the moment the error is detected.

diag_verbose

Set the verbosity of the output triggered by auto_diag. Currently only adds the current input-record-number (if known) to the diagnostic output with an indication of the position of the error.

callbacks

See the "Callbacks" section below.

To sum it up,

 $csv = Text::CSV_XS->new ();

is equivalent to

 $csv = Text::CSV_XS->new ({
     quote_char            => '"',
     escape_char           => '"',
     sep_char              => ',',
     eol                   => $\,
     always_quote          => 0,
     quote_space           => 1,
     quote_null            => 1,
     quote_binary          => 1,
     binary                => 0,
     decode_utf8           => 1,
     keep_meta_info        => 0,
     allow_loose_quotes    => 0,
     allow_loose_escapes   => 0,
     allow_unquoted_escape => 0,
     allow_whitespace      => 0,
     blank_is_undef        => 0,
     empty_is_undef        => 0,
     verbatim              => 0,
     auto_diag             => 0,
     diag_verbose          => 0,
     callbacks             => undef,
     });

For all of the above mentioned flags, an accessor method is available where you can inquire the current value, or change the value

 my $quote = $csv->quote_char;
 $csv->binary (1);

It is not wise to change these settings halfway through writing CSV data to a stream. If however you want to create a new stream using the available CSV object, there is no harm in changing them.

If the "new" constructor call fails, it returns undef, and makes the fail reason available through the "error_diag" method.

 $csv = Text::CSV_XS->new ({ ecs_char => 1 }) or
     die "".Text::CSV_XS->error_diag ();

"error_diag" will return a string like

 "INI - Unknown attribute 'ecs_char'"

print

 $status = $csv->print ($io, $colref);

Similar to "combine" + "string" + "print", but much more efficient. It expects an array ref as input (not an array!) and the resulting string is not really created, but immediately written to the $io object, typically an IO handle or any other object that offers a "print" method.

For performance reasons print does not create a result string, so all "string", "status", "fields", and "error_input" methods will return undefined information after executing this method.

If $colref is undef (explicit, not through a variable argument) and "bind_columns" was used to specify fields to be printed, it is possible to make performance improvements, as otherwise data would have to be copied as arguments to the method call:

 $csv->bind_columns (\($foo, $bar));
 $status = $csv->print ($fh, undef);

A short benchmark

 my @data = ("aa" .. "zz");
 $csv->bind_columns (\(@data));

 $csv->print ($io, [ @data ]);   # 11800 recs/sec
 $csv->print ($io,  \@data  );   # 57600 recs/sec
 $csv->print ($io,   undef  );   # 48500 recs/sec

combine

 $status = $csv->combine (@columns);

This method constructs a CSV string from @columns, returning success or failure. Failure can result from lack of arguments or an argument that contains an invalid character. Upon success, "string" can be called to retrieve the resultant CSV string. Upon failure, the value returned by "string" is undefined and "error_input" could be called to retrieve the invalid argument.

string

 $line = $csv->string ();

This method returns the input to "parse" or the resultant CSV string of "combine", whichever was called more recently.

getline

 $colref = $csv->getline ($io);

This is the counterpart to "print", as "parse" is the counterpart to "combine": it parses a row from the $io handle using the "getline" method associated with $io and parses this row into an array ref. This array ref is returned by the function or undef for failure. When $io does not support getline, you are likely to hit errors.

When fields are bound with "bind_columns" the return value is a reference to an empty list.

The "string", "fields", and "status" methods are meaningless again.

getline_all

 $arrayref = $csv->getline_all ($io);
 $arrayref = $csv->getline_all ($io, $offset);
 $arrayref = $csv->getline_all ($io, $offset, $length);

This will return a reference to a list of getline ($io) results. In this call, keep_meta_info is disabled. If $offset is negative, as with splice, only the last abs ($offset) records of $io are taken into consideration.

Given a CSV file with 10 lines:

 lines call
 ----- ---------------------------------------------------------
 0..9  $csv->getline_all ($io)         # all
 0..9  $csv->getline_all ($io,  0)     # all
 8..9  $csv->getline_all ($io,  8)     # start at 8
 -     $csv->getline_all ($io,  0,  0) # start at 0 first 0 rows
 0..4  $csv->getline_all ($io,  0,  5) # start at 0 first 5 rows
 4..5  $csv->getline_all ($io,  4,  2) # start at 4 first 2 rows
 8..9  $csv->getline_all ($io, -2)     # last 2 rows
 6..7  $csv->getline_all ($io, -4,  2) # first 2 of last  4 rows

parse

 $status = $csv->parse ($line);

This method decomposes a CSV string into fields, returning success or failure. Failure can result from a lack of argument or the given CSV string is improperly formatted. Upon success, "fields" can be called to retrieve the decomposed fields. Upon failure calling "fields" will return undefined data and "error_input" can be called to retrieve the invalid argument.

You may use the "types" method for setting column types. See "types"' description below.

getline_hr

The "getline_hr" and "column_names" methods work together to allow you to have rows returned as hashrefs. You must call "column_names" first to declare your column names.

 $csv->column_names (qw( code name price description ));
 $hr = $csv->getline_hr ($io);
 print "Price for $hr->{name} is $hr->{price} EUR\n";

"getline_hr" will croak if called before "column_names".

Note that "getline_hr" creates a hashref for every row and will be much slower than the combined use of "bind_columns" and "getline" but still offering the same ease of use hashref inside the loop:

 my @cols = @{$csv->getline ($io)};
 $csv->column_names (@cols);
 while (my $row = $csv->getline_hr ($io)) {
     print $row->{price};
     }

Could easily be rewritten to the much faster:

 my @cols = @{$csv->getline ($io)};
 my $row = {};
 $csv->bind_columns (\@{$row}{@cols});
 while ($csv->getline ($io)) {
     print $row->{price};
     }

Your mileage may vary for the size of the data and the number of rows. With perl-5.14.2 the comparison for a 100_000 line file with 14 rows:

            Rate hashrefs getlines
 hashrefs 1.00/s       --     -76%
 getlines 4.15/s     313%       --

getline_hr_all

 $arrayref = $csv->getline_hr_all ($io);
 $arrayref = $csv->getline_hr_all ($io, $offset);
 $arrayref = $csv->getline_hr_all ($io, $offset, $length);

This will return a reference to a list of getline_hr ($io) results. In this call, keep_meta_info is disabled.

print_hr

 $csv->print_hr ($io, $ref);

Provides an easy way to print a $ref (as fetched with "getline_hr") provided the column names are set with "column_names".

It is just a wrapper method with basic parameter checks over

 $csv->print ($io, [ map { $ref->{$_} } $csv->column_names ]);

fragment

This function tries to implement RFC7111 (URI Fragment Identifiers for the text/csv Media Type) - http://tools.ietf.org/html/rfc7111

 my $AoA = $csv->fragment ($io, $spec);

In specifications, * is used to specify the last item, a dash (-) to indicate a range. All indices are 1-based: the first row or column has index 1. Selections can be combined with the semi-colon (;).

When using this method in combination with "column_names", the returned reference will point to a list of hashes instead of a list of lists. A disjointed cell-based combined selection might return rows with different number of columns making the use of hashes unpredictable.

 $csv->column_names ("Name", "Age");
 my $AoH = $csv->fragment ($io, "col=3;8");

If the "after_parse" callback is active, it is also called on every line parsed and skipped before the fragment.

row
 row=4
 row=5-7
 row=6-*
 row=1-2;4;6-*
col
 col=2
 col=1-3
 col=4-*
 col=1-2;4;7-*
cell

In cell-based selection, the comma (,) is used to pair row and column

 cell=4,1

The range operator (-) using cells can be used to define top-left and bottom-right cell location

 cell=3,1-4,6

The * is only allowed in the second part of a pair

 cell=3,2-*,2    # row 3 till end, only column 2
 cell=3,2-3,*    # column 2 till end, only row 3
 cell=3,2-*,*    # strip row 1 and 2, and column 1

Cells and cell ranges may be combined with ;, possibly resulting in rows with different number of columns

 cell=1,1-2,2;3,3-4,4;1,4;4,1

Disjointed selections will only return selected cells. The cells that are not specified will not be included in the returned set, not even as undef. As an example given a CSV like

 11,12,13,...19
 21,22,...28,29
 :            :
 91,...97,98,99

with cell=1,1-2,2;3,3-4,4;1,4;4,1 will return:

 11,12,14
 21,22
 33,34
 41,43,44

Overlapping cell-specs will return those cells only once, So cell=1,1-3,3;2,2-4,4;2,3;4,2 will return:

 11,12,13
 21,22,23,24
 31,32,33,34
 42,43,44

RFC7111 does not allow different types of specs to be combined (either row or col or cell). Passing an invalid fragment specification will croak and set error 2013.

column_names

Set the "keys" that will be used in the "getline_hr" calls. If no keys (column names) are passed, it will return the current setting as a list.

"column_names" accepts a list of scalars (the column names) or a single array_ref, so you can pass the return value from "getline" too:

 $csv->column_names ($csv->getline ($io));

"column_names" does no checking on duplicates at all, which might lead to unexpected results. Undefined entries will be replaced with the string "\cAUNDEF\cA", so

 $csv->column_names (undef, "", "name", "name");
 $hr = $csv->getline_hr ($io);

Will set $hr->{"\cAUNDEF\cA"} to the 1st field, $hr->{""} to the 2nd field, and $hr->{name} to the 4th field, discarding the 3rd field.

"column_names" croaks on invalid arguments.

bind_columns

Takes a list of scalar references to be used for output with "print" or to store in the fields fetched by "getline". When you do not pass enough references to store the fetched fields in, "getline" will fail with error 3006. If you pass more than there are fields to return, the content of the remaining references is left untouched.

 $csv->bind_columns (\$code, \$name, \$price, \$description);
 while ($csv->getline ($io)) {
     print "The price of a $name is \x{20ac} $price\n";
     }

To reset or clear all column binding, call "bind_columns" with the single argument undef. This will also clear column names.

 $csv->bind_columns (undef);

If no arguments are passed at all, "bind_columns" will return the list of current bindings or undef if no binds are active.

eof

 $eof = $csv->eof ();

If "parse" or "getline" was used with an IO stream, this method will return true (1) if the last call hit end of file, otherwise it will return false (''). This is useful to see the difference between a failure and end of file.

types

 $csv->types (\@tref);

This method is used to force that (all) columns are of a given type. For example, if you have an integer column, two columns with doubles and a string column, then you might do a

 $csv->types ([Text::CSV_XS::IV (),
               Text::CSV_XS::NV (),
               Text::CSV_XS::NV (),
               Text::CSV_XS::PV ()]);

Column types are used only for decoding columns while parsing, in other words by the "parse" and "getline" methods.

You can unset column types by doing a

 $csv->types (undef);

or fetch the current type settings with

 $types = $csv->types ();
IV

Set field type to integer.

NV

Set field type to numeric/float.

PV

Set field type to string.

fields

 @columns = $csv->fields ();

This method returns the input to "combine" or the resultant decomposed fields of a successful "parse", whichever was called more recently.

Note that the return value is undefined after using "getline", which does not fill the data structures returned by "parse".

meta_info

 @flags = $csv->meta_info ();

This method returns the "flags" of the input to "combine" or the flags of the resultant decomposed fields of "parse", whichever was called more recently.

For each field, a meta_info field will hold flags that inform something about the field returned by the "fields" method or passed to the "combine" method. The flags are bit-wise-or'd like:

0x0001

The field was quoted.

0x0002

The field was binary.

See the is_*** methods below.

is_quoted

 my $quoted = $csv->is_quoted ($column_idx);

Where $column_idx is the (zero-based) index of the column in the last result of "parse".

This returns a true value if the data in the indicated column was enclosed in quote_char quotes. This might be important for fields where content ,20070108, is to be treated as a numeric value, and where ,"20070108", is explicitly marked as character string data.

is_binary

 my $binary = $csv->is_binary ($column_idx);

Where $column_idx is the (zero-based) index of the column in the last result of "parse".

This returns a true value if the data in the indicated column contained any byte in the range [\x00-\x08,\x10-\x1F,\x7F-\xFF].

is_missing

 my $missing = $csv->is_missing ($column_idx);

Where $column_idx is the (zero-based) index of the column in the last result of "getline_hr".

 $csv->keep_meta_info (1);
 while (my $hr = $csv->getline_hr ($fh)) {
     $csv->is_missing (0) and next; # This was an empty line
     }

When using "getline_hr", it is impossible to tell if the parsed fields are undef because they where not filled in the CSV stream or because they were not read at all, as all the fields defined by "column_names" are set in the hash-ref. If you still need to know if all fields in each row are provided, you should enable keep_meta_info so you can check the flags.

status

 $status = $csv->status ();

This method returns success (or failure) of the last invoked "combine" or "parse" call.

error_input

 $bad_argument = $csv->error_input ();

This method returns the erroneous argument (if it exists) of "combine" or "parse", whichever was called more recently. If the last invocation was successful, error_input will return undef.

error_diag

 Text::CSV_XS->error_diag ();
 $csv->error_diag ();
 $error_code           = 0  + $csv->error_diag ();
 $error_str            = "" . $csv->error_diag ();
 ($cde, $str, $pos, $recno) = $csv->error_diag ();

If (and only if) an error occurred, this function returns the diagnostics of that error.

If called in void context, this will print the internal error code and the associated error message to STDERR.

If called in list context, this will return the error code and the error message in that order. If the last error was from parsing, the third value returned is a best guess at the location within the line that was being parsed. Its value is 1-based. The fourth value represents the record count parsed by this csv instance. See examples/csv-check for how this can be used.

If called in scalar context, it will return the diagnostics in a single scalar, a-la $!. It will contain the error code in numeric context, and the diagnostics message in string context.

When called as a class method or a direct function call, the diagnostics are that of the last "new" call.

record_number

 $recno = $csv->record_number ();

Returns the records parsed by this csv instance. This value should be more accurate than $. when embedded newlines come in play. Records written by this instance are not counted.

SetDiag

 $csv->SetDiag (0);

Use to reset the diagnostics if you are dealing with errors.

FUNCTIONS ^

csv

This function is not exported by default and should be explicitly requested:

 use Text::CSV_XS qw( csv );

This is the second draft. This function will stay, but the arguments might change based on user feedback.

This is an high-level function that aims at simple (user) interfaces. This can be used to read/parse a CSV file or stream (the default behavior) or to produce a file or write to a stream (define the out attribute). It returns an array- or hash-reference on parsing (or undef on fail) or the numeric value of "error_diag" on writing. When this function fails you can get to the error using the class call to "error_diag"

 my $aoa = csv (in => "test.csv") or
     die Text::CSV_XS->error_diag;

This function takes the arguments as key-value pairs. This can be passed as a list or as an anonymous hash:

 my $aoa = csv (  in => "test.csv", sep_char => ";");
 my $aoh = csv ({ in => $fh, headers => "auto" });

The arguments passed consist of two parts: the arguments to "csv" itself and the optional attributes to the CSV object used inside the function as enumerated and explained in "new".

If not overridden, the default option used for CSV is

 auto_diag => 1

The option that is always set and cannot be altered is

 binary    => 1

in

Used to specify the source. in can be a file name (e.g. "file.csv"), which will be opened for reading and closed when finished, a file handle (e.g. $fh or FH), a reference to a glob (e.g. \*ARGV), the glob itself (e.g. *STDIN), or a reference to a scalar (e.g. \q{1,2,"csv"}).

When used with "out", in should be a reference to a CSV structure (AoA or AoH) or a CODE-ref that returns an array-reference or a hash-reference. The code-ref will be invoked with no arguments and .

 my $aoa = csv (in => "file.csv");

 open my $fh, "<", "file.csv";
 my $aoa = csv (in => $fh);

 my $csv = [ [qw( Foo Bar )], [ 1, 2 ], [ 2, 3 ]];
 my $err = csv (in => $csv, out => "file.csv");

out

In output mode, the default CSV options when producing CSV are

 eol       => "\r\n"

The "fragment" attribute is ignored in output mode.

out can be a file name (e.g. "file.csv"), which will be opened for writing and closed when finished, a file handle (e.g. $fh or FH), a reference to a glob (e.g. \*STDOUT), or the glob itself (e.g. *STDOUT).

 csv (in => sub { $sth->fetch },            out => "dump.csv");
 csv (in => sub { $sth->fetchrow_hashref }, out => "dump.csv",
      headers => $sth->{NAME_lc});

When a code-ref is used, the output is generated per invocation, so no buffering is involved. This implies that there is no size restriction on the number of records. The function ends when the coderef returns a false value.

encoding

If passed, it should be an encoding accepted by the :encoding() option to open. There is no default value. This attribute does not work in perl 5.6.x.

headers

If this attribute is not given, the default behavior is to produce an array of arrays.

If headers is supplied, it should be either an anonymous list of column names or a flag: auto or skip. When skip is used, the header will not be included in the output.

 my $aoa = csv (in => $fh, headers => "skip");

If auto is used, the first line of the CSV source will be read as the list of field headers and used to produce an array of hashes.

 my $aoh = csv (in => $fh, headers => "auto");

If headers is an anonymous list, the entries in the list will be used instead

 my $aoh = csv (in => $fh, headers => [qw( Foo Bar )]);
 csv (in => $aoa, out => $fh, headers => [qw( code description price }]);

fragment

Only output the fragment as defined in the "fragment" method. This option is ignored when generating CSV. See "out".

Combining all of them could give something like

 use Text::CSV_XS qw( csv );
 my $aoh = csv (
     in       => "test.txt",
     encoding => "utf-8",
     headers  => "auto",
     sep_char => "|",
     fragment => "row=3;6-9;15-*",
     );
 say $aoh->[15]{Foo};

Callbacks

Callbacks enable actions triggered from the inside of Text::CSV_XS.

While most of what this enables can easily be done in an unrolled loop as described in the "SYNOPSIS" callbacks can be used to meet special demands or enhance the "csv" function.

error
 $csv->callbacks (error => sub { $csv->SetDiag (0) });

the error callback is invoked when an error occurs, but only when "auto_diag" is set to a true value. A callback is invoked with the values returned by "error_diag":

 my ($c, $s);

 sub ignore3006
 {
     my ($err, $msg, $pos, $recno) = @_;
     if ($err == 3006) {
         # ignore this error
         ($c, $s) = (undef, undef);
         SetDiag (0);
         }
     # Any other error
     return;
     } # ignore3006

 $csv->callbacks (error => \&ignore3006);
 $csv->bind_columns (\$c, \$s);
 while ($csv->getline ($fh)) {
     # Error 3006 will not stop the loop
     }
after_parse
 $csv->callbacks (after_parse => sub { push @{$_[1]}, "NEW" });
 while (my $row = $csv->getline ($fh)) {
     $row->[-1] eq "NEW";
     }

This callback is invoked after parsing with "getline" only if no error occurred. The callback is invoked with two arguments: the current CSV parser object and an array reference to the fields parsed.

The return code of the callback is ignored.

 sub add_from_db
 {
     my ($csv, $row) = @_;
     $sth->execute ($row->[4]);
     push @$row, $sth->fetchrow_array;
     } # add_from_db

 my $aoa = csv (in => "file.csv", callbacks => {
     after_parse => \&add_from_db });
before_print
 my $idx = 1;
 $csv->callbacks (before_print => sub { $_[1][0] = $idx++ });
 $csv->print (*STDOUT, [ 0, $_ ]) for @members;

This callback is invoked before printing with "print" only if no error occurred. The callback is invoked with two arguments: the current CSV parser object and an array reference to the fields passed.

The return code of the callback is ignored.

 sub max_4_fields
 {
     my ($csv, $row) = @_;
     @$row > 4 and splice @$row, 4;
     } # max_4_fields

 csv (in => csv (in => "file.csv"), out => *STDOUT,
     callbacks => { before print => \&max_4_fields });

This callback is not active for "combine".

Callbacks for csv ()

The "csv" allows for some callbacks that do not integrate in XS internals but only feature the "csv" function.

  csv (in        => "file.csv",
       callbacks => {
           after_parse  => sub { say "AFTER PARSE";  }, # first
           after_in     => sub { say "AFTER IN";     }, # second
           on_in        => sub { say "ON IN";        }, # third
           },
       );

  csv (in        => $aoh,
       out       => "file.csv",
       callbacks => {
           on_in        => sub { say "ON IN";        }, # first
           before_out   => sub { say "BEFORE OUT";   }, # second
           before_print => sub { say "BEFORE PRINT"; }, # third
           },
       );
after_in

This callback is invoked for each record after all records have been parsed but before returning the reference to the caller. The hook is invoked with two arguments: the current CSV parser object and a reference to the record. The reference can be a reference to a HASH or a reference to an ARRAY as determined by the arguments.

This callback can also be passed as an attribute without the callbacks wrapper.

before_out

This callback is invoked for each record before the record is printed. The hook is invoked with two arguments: the current CSV parser object and a reference to the record. The reference can be a reference to a HASH or a reference to an ARRAY as determined by the arguments.

This callback can also be passed as an attribute without the callbacks wrapper.

on_in

This callback acts exactly as the "after_in" or the "before_out" hooks.

This callback can also be passed as an attribute without the callbacks wrapper.

INTERNALS ^

Combine (...)
Parse (...)

The arguments to these internal functions are deliberately not described or documented in order to enable the module authors make changes it when they feel the need for it. Using them is highly discouraged as the API may change in future releases.

EXAMPLES ^

Reading a CSV file line by line:

 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
 open my $fh, "<", "file.csv" or die "file.csv: $!";
 while (my $row = $csv->getline ($fh)) {
     # do something with @$row
     }
 close $fh or die "file.csv: $!";

Reading only a single column

 my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });
 open my $fh, "<", "file.csv" or die "file.csv: $!";
 # get only the 4th column
 my @column = map { $_->[3] } @{$csv->getline_all ($fh)};
 close $fh or die "file.csv: $!";

with "csv", you could do

 my @column = map { $_->[0] }
     @{csv (in => "file.csv", fragment => "col=4")};

Parsing CSV strings:

 my $csv = Text::CSV_XS->new ({ keep_meta_info => 1, binary => 1 });

 my $sample_input_string =
     qq{"I said, ""Hi!""",Yes,"",2.34,,"1.09","\x{20ac}",};
 if ($csv->parse ($sample_input_string)) {
     my @field = $csv->fields;
     foreach my $col (0 .. $#field) {
         my $quo = $csv->is_quoted ($col) ? $csv->{quote_char} : "";
         printf "%2d: %s%s%s\n", $col, $quo, $field[$col], $quo;
         }
     }
 else {
     print STDERR "parse () failed on argument: ",
         $csv->error_input, "\n";
     $csv->error_diag ();
     }

Printing CSV data

The fast way: using "print"

An example for creating CSV files using the "print" method:

 my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ });
 open my $fh, ">", "foo.csv" or die "foo.csv: $!";
 for (1 .. 10) {
     $csv->print ($fh, [ $_, "$_" ]) or $csv->error_diag;
     }
 close $fh or die "$tbl.csv: $!";

The slow way: using "combine" and "string"

or using the slower "combine" and "string" methods:

 my $csv = Text::CSV_XS->new;

 open my $csv_fh, ">", "hello.csv" or die "hello.csv: $!";

 my @sample_input_fields = (
     'You said, "Hello!"',   5.67,
     '"Surely"',   '',   '3.14159');
 if ($csv->combine (@sample_input_fields)) {
     print $csv_fh $csv->string, "\n";
     }
 else {
     print "combine () failed on argument: ",
         $csv->error_input, "\n";
     }
 close $csv_fh or die "hello.csv: $!";

Rewriting CSV

Rewrite CSV files with ; as separator character to well-formed CSV:

 use Text::CSV_XS qw( csv );
 csv (in => csv (in => "bad.csv", sep_char => ";"), out => *STDOUT);

Dumping database tables to CSV

Dumping a database table can be simple as this (TIMTOWTDI):

 my $dbh = DBI->connect (...);
 my $sql = "select * from foo";

 # using your own loop
 open my $fh, ">", "foo.csv" or die "foo.csv: $!\n";
 my $csv = Text::CSV_XS->new ({ binary => 1, eol => "\r\n" });
 my $sth = $dbh->prepare ($sql); $sth->execute;
 $csv->print ($fh, $sth->{NAME_lc});
 while (my $row = $sth->fetch) {
     $csv->print ($fh, $row);
     }

 # using the csv function, all in memory
 csv (out => "foo.csv", in => $dbh->selectall_arrayref ($sql));

 # using the csv function, streaming with callbacks
 my $sth = $dbh->prepare ($sql); $sth->execute;
 csv (out => "foo.csv", in => sub { $sth->fetch            });
 csv (out => "foo.csv", in => sub { $sth->fetchrow_hashref });

The examples folder

For more extended examples, see the examples/ 1) sub-directory in the original distribution or the git repository 2).

 1. http://repo.or.cz/w/Text-CSV_XS.git?a=tree;f=examples
 2. http://repo.or.cz/w/Text-CSV_XS.git

The following files can be found there:

parser-xs.pl

This can be used as a boilerplate to parse invalid CSV and parse beyond (expected) errors alternative to using the "error" callback.

 $ perl examples/parser-xs.pl bad.csv >good.csv
csv-check

This is a command-line tool that uses parser-xs.pl techniques to check the CSV file and report on its content.

 $ csv-check files/utf8.csv
 Checked with examples/csv-check 1.5 using Text::CSV_XS 0.81
 OK: rows: 1, columns: 2
     sep = <,>, quo = <">, bin = <1>
csv2xls

A script to convert CSV to Microsoft Excel. This requires Date::Calc and Spreadsheet::WriteExcel. The converter accepts various options and can produce UTF-8 Excel files.

csvdiff

A script that provides colorized diff on sorted CSV files, assuming first line is header and first field is the key. Output options include colorized ANSI escape codes or HTML.

 $ csvdiff --html --output=diff.html file1.csv file2.csv

CAVEATS ^

Text::CSV_XS is not designed to detect the characters used to quote and separate fields. The parsing is done using predefined (default) settings. In the examples sub-directory, you can find scripts that demonstrate how you could try to detect these characters yourself.

Microsoft Excel

The import/export from Microsoft Excel is a risky task, according to the documentation in Text::CSV::Separator. Microsoft uses the system's list separator defined in the regional settings, which happens to be a semicolon for Dutch, German and Spanish (and probably some others as well). For the English locale, the default is a comma. In Windows however, the user is free to choose a predefined locale, and then change every individual setting in it, so checking the locale is no solution.

TODO ^

More Errors & Warnings

New extensions ought to be clear and concise in reporting what error has occurred where and why, and maybe also offer a remedy to the problem.

"error_diag" is a (very) good start, but there is more work to be done in this area.

Basic calls should croak or warn on illegal parameters. Errors should be documented.

setting meta info

Future extensions might include extending the "meta_info", "is_quoted", and "is_binary" to accept setting these flags for fields, so you can specify which fields are quoted in the "combine"/"string" combination.

 $csv->meta_info (0, 1, 1, 3, 0, 0);
 $csv->is_quoted (3, 1);

Metadata Vocabulary for Tabular Data (a W3C editor's draft) could be an example for supporting more metadata.

Parse the whole file at once

Implement new methods or functions that enable parsing of a complete file at once, returning a list of hashes. Possible extension to this could be to enable a column selection on the call:

 my @AoH = $csv->parse_file ($filename, { cols => [ 1, 4..8, 12 ]});

Returning something like

 [ { fields => [ 1, 2, "foo", 4.5, undef, "", 8 ],
     flags  => [ ... ],
     },
   { fields => [ ... ],
     .
     },
   ]

Note that the "csv" function already supports most of this, but does not return flags. "getline_all" returns all rows for an open stream, but this will not return flags either. "fragment" can reduce the required rows or columns, but cannot combine them.

Cookbook

Write a document that has recipes for most known non-standard (and maybe some standard) CSV formats, including formats that use TAB, ;, |, or other non-comma separators.

Examples could be taken from W3C's CSV on the Web: Use Cases and Requirements

NOT TODO

combined methods

Requests for adding means (methods) that combine "combine" and "string" in a single call will not be honored (use "print" instead). Likewise for "parse" and "fields" (use "getline" instead), given the problems with embedded newlines.

Release plan

No guarantees, but this is what I had in mind some time ago:

next
 - DIAGNOSTICS section in pod to *describe* the errors (see below)

EBCDIC ^

The current hard-coding of characters and character ranges makes this code unusable on EBCDIC systems. Recent work in perl-5.20 might change that.

Opening EBCDIC encoded files on ASCII+ systems is likely to succeed using Encode's cp37, cp1047, or posix-bc:

 open my $fh, "<:encoding(cp1047)", "ebcdic_file.csv" or die "...";

DIAGNOSTICS ^

Still under construction ...

If an error occurs, $csv->error_diag can be used to get information on the cause of the failure. Note that for speed reasons the internal value is never cleared on success, so using the value returned by "error_diag" in normal cases - when no error occurred - may cause unexpected results.

If the constructor failed, the cause can be found using "error_diag" as a class method, like Text::CSV_XS->error_diag.

The $csv->error_diag method is automatically invoked upon error when the contractor was called with auto_diag set to 1 or 2, or when autodie is in effect. When set to 1, this will cause a warn with the error message, when set to 2, it will die. 2012 - EOF is excluded from auto_diag reports.

Errors can be (individually) caught using the "error" callback.

The errors as described below are available. I have tried to make the error itself explanatory enough, but more descriptions will be added. For most of these errors, the first three capitals describe the error category:

And below should be the complete list of error codes that can be returned:

SEE ALSO ^

IO::File, IO::Handle, IO::Wrap, Text::CSV, Text::CSV_PP, Text::CSV::Encoded, Text::CSV::Separator, Spreadsheet::CSV and Spreadsheet::Read, and of course perl.

AUTHOR ^

Alan Citterman <alan@mfgrtl.com> wrote the original Perl module. Please don't send mail concerning Text::CSV_XS to Alan, who is not involved in the C/XS part that is now the main part of the module.

Jochen Wiedmann <joe@ispsoft.de> rewrote the en- and decoding in C by implementing a simple finite-state machine. He added variable quote, escape and separator characters, the binary mode and the print and getline methods. See ChangeLog releases 0.10 through 0.23.

H.Merijn Brand <h.m.brand@xs4all.nl> cleaned up the code, added the field flags methods, wrote the major part of the test suite, completed the documentation, fixed most RT bugs, added all the allow flags and the "csv" function. See ChangeLog releases 0.25 and on.

COPYRIGHT AND LICENSE ^

 Copyright (C) 2007-2014 H.Merijn Brand.  All rights reserved.
 Copyright (C) 1998-2001 Jochen Wiedmann. All rights reserved.
 Copyright (C) 1997      Alan Citterman.  All rights reserved.

This library is free software; you can redistribute and/or modify it under the same terms as Perl itself.

syntax highlighting: