NAME
Parse::CSV - Highly flexible CVS parser for large files
SYNOPSIS
# Simple headerless comma-seperated column parser
my $simple = Parse::CSV->new(
file => 'file.csv',
);
while ( my $array_ref = $simple->fetch ) {
# Do something...
}
# Parse a colon-seperated variables file from a filehandle as a hash
# based on headers from the first line.
# Then filter, so we emit objects rather than the plain hash.
my $objects = Parse::CSV->new(
filehandle => $io_handle,
sep_char => ';',
fields => 'auto',
filter => sub { My::Object->new( $_ ) },
);
while ( my $object = $objects->fetch ) {
$object->do_something;
}
DESCRIPTION
Surely the CPAN doesn't need yet another CSV parsing module.
Text::CSV_XS is the standard parser for CSV files. It is fast as hell, but unfortunately it can be a bit verbose to use.
A number of other modules attempt to put usability wrappers around this venerable module, but they all tend to focus on parsing the entire file at once.
This is fine unless your CSV files start to get large. For that case, you have only the heavyweight XML::SAXDriver::CSV option.
Parse::CSV is intended to fill this gap, and provide a light-weight, flexible and customisable incremental parser for large CSV files.
Main Features
Incremental Parsing - To reduce memory load, all parsing is done incrementally.
Array Mode - Parsing can be done in simple array mode, returning a reference to an array if the columns are not named.
Hash Mode - Parsing can be done in hash mode, putting the data into a hash and return a reference to it.
Filter Capability
- All items returned can be pass through a custom filter. This filter can either modify the data on the fly, or drop records you don't need.
Writing Filters
A Parse::CSV filter is a subroutine reference that is passed the raw record as $_
, and should return
the alternative or modified record to return to the user.
The basic null filter (does not modify or drop any records thus looks like the following).
sub { $_ };
A filter which reversed the order of the columns (assuming they are passed as an array) might look like the following.
sub { return [ reverse @$_ ] };
To drop the record, you should return undef
from the filter. The parser will then keep pulling and parsing new records until one passes the filter.
# Only keep records where foo is true
sub { $_->{foo} ? $_ : undef }
To signal an error, throw an exception
sub {
$_->{foo} =~ /bar/ or die "Assumption failed";
return $_;
}
METHODS
new
The new
constructor creates and initialise a new CSV parser.
It takes a number of params.
To specify the CSV data source, you should provide either the file
param, which should be the name of the file to read, or the handle
param, which should be a file handle to read instead.
The actual parsing is done using Text::CSV_XS. Any of it's constructor/parsing params can also be provided to this new
method, and they will be passed on.
Alternatively, they can be passed as a single HASH
reference as the csv_attr
param. For example:
$parser = Parse::CSV->new(
file => 'file.csv',
csv_attr => {
sep_char => ';',
quote_char => "'",
},
);
An optional fields
param can be provided, which should be an array reference containing the names of the columns in the CSV file.
$parser = Parse::CSV->new(
file => 'file.csv',
fields => [ 'col1', 'col2', 'col3' ],
);
If the fields
param is provided, the parser will map the columns to a hash where the keys are the field names provided, and the values are the values found in the CSV file.
If the fields
param is not provided, the parser will return simple array references of the columns.
If the fields
param is the string 'auto', the fields will be automatically determined by reading the first line of the CSV file and using those values as the field names.
The optional filter
param will be used to filter the records if provided. It should be a CODE
reference or any otherwise callable scalar, and each value parsed (either array reference or hash reference) will be passed to the filter to be changed or converted into an object, or whatever you wish.
Returns a new Parse::CSV object, or throws an exception (dies) on error.
fetch
Once a Parse::CSV object has been created, the fetch
method is used to parse and return the next value from the CSV file.
Returns an ARRAY
, HASH
or the output of the filter, based on the configuration of the object, or undef
in a variety of situations.
Returning undef
means either some part of the parsing and filtering process has resulted in an error, or that the end of file has been reached.
On receiving undef
, you should the errstr
method. If it is a null string you have reached the end of file. Otherwise the error message will be returned. Thus, the basic usage of Parse::CSV will look like the following.
my $parser = Parse::CSV->new(
file => 'file.csv',
);
while ( my $value = $parser->fetch ) {
# Do something...
}
if ( $parser->errstr ) {
# Handle errors...
}
row
The row
method returns the current row of the CSV file.
This is a one-based count, so when you first create the parser, the value of row
will be zero (unless you are using fields =
'auto'> in which case it will be 1).
errstr
On error, the errstr
method returns the error that occured.
If the last action was NOT an error, returns the null string ''
.
SUPPORT
Bugs should be always be reported via the CPAN bug tracker at
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Parse-CSV
For other issues, or commercial enhancement or support, contact the author.
AUTHORS
Adam Kennedy <adamk@cpan.org<
SEE ALSO
COPYRIGHT
Copyright (c) 2006 Adam Kennedy.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.