The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Tie::Handle::CSV - easy access to CSV files

VERSION

Version 0.12

SYNOPSIS

use strict;
use warnings;

use Tie::Handle::CSV;

my $csv_fh = Tie::Handle::CSV->new('basic.csv', header => 1);

print $csv_fh->header, "\n";

while (my $csv_line = <$csv_fh>)
   {
   $csv_line->{'salary'} *= 1.05;  ## give a 5% raise
   print $csv_line, "\n";          ## auto-stringify to CSV line on STDOUT
   }

close $csv_fh;

DESCRIPTION

Tie::Handle::CSV makes basic access to CSV files easier.

Features

Auto-parse CSV line

When you read from the tied handle, the next line from your CSV is parsed and returned as a data structure ready for access. In the example below $csv_line is a hash reference with the column names for keys and the values being the corresponding data from the second line of the file.

my $csv_fh = Tie::Handle::CSV->new('foo.csv', header => 1);
my $csv_line = <$csv_fh>;
print $csv_line->{'Id'};

In the above example $csv_line is a hash reference because the tied handle was declared as having a header. If the CSV file does not have a header the line is parsed and returned as an array reference:

my $csv_fh = Tie::Handle::CSV->new('bar.csv', header => 0);
my $csv_line = <$csv_fh>;
print $csv->[0];

Auto-stringify to CSV format

When you use the $csv_line in a string context it is automatically reconstituted as a CSV line.

print $csv_line, "\n";  ## prints "123,abc,xyz\n"

EXAMPLES

Assume basic.csv contains:

name,salary,job
steve,20000,picker
dee,19000,checker

The following script uppercases the first letter of everyone's name, increases their salary by 5% and prints the modified CSV data to STDOUT.

my $csv_fh = Tie::Handle::CSV->new('basic.csv', header => 1);
while (my $csv_line = <$csv_fh>)
   {
   $csv_line->{'name'} = ucfirst $csv_line->{'name'};
   $csv_line->{'salary'} *= 1.05;
   print $csv_line . "\n";
   }
close $csv_fh;

The converted output on STDOUT would appear as:

Steve,21000,picker
Dee,19950,checker

METHODS

new

my $csv_fh = Tie::Handle::CSV->new('basic.csv');

The new method returns a tied filehandle. The default options would make the above equivalent to:

my $csv_fh = Tie::Handle::CSV->new( csv_parser   => Text::CSV_XS->new(),
                                    file         => 'basic.csv',
                                    header       => 1,
                                    key_case     => undef,
                                    open_mode    => undef,
                                    sep_char     => undef,
                                    simple_reads => undef );

The options to new are discussed in detail below.

csv_parser

Internally, Text::CSV_XS is used to do CSV parsing and construction. By default the Text::CSV_XS instance is instantiated with no arguments. If other behaviors are desired, you can create your own instance and pass it as the value to this option.

## use colon separators
my $csv_parser = Text::CSV_XS->new( { sep_char => ':' } );
my $csv_fh = Tie::Handle::CSV->new( 'basic.csv',
                                     csv_parser => $csv_parser );

file

This option specifies the path to the CSV file. As an alternative, the file key can be omitted. When there are an odd number of arguments the first argument is taken to be the file name. If this option is given in conjunction with an odd number of arguments, the first argument takes precedence over this option.

## same results
my $csv_fh = Tie::Handle::CSV->new( 'basic.csv' );
my $csv_fh = Tie::Handle::CSV->new( file => 'basic.csv' );

If you already have an open file, you can pass the GLOB reference as the file value. This might allow you to act on STDIN, or another tied handle.

my $csv_fh = Tie::Handle::CSV->new( \*STDIN );

This option controls whether headers are to be used. If it is false, lines will be represented as array references.

## no header
my $csv_fh = Tie::Handle::CSV->new( 'no_header.csv', header => 0 );
## print first field of first line
my $csv_line = <$csv_fh>;
print $csv_line->[0], "\n";

If this option is true, and not an array reference the values from the first line of the file are used as the keys in the hash references returned from subsequent line reads.

## header in file
my $csv_fh = Tie::Handle::CSV->new( 'header.csv' );
## print 'name' value from first line
my $csv_line = <$csv_fh>;
print $csv_line->{'name'}, "\n";

If the value for this option is an array reference, the values in the array reference are used as the keys in the hash reference representing the line of data.

## header passed as arg
my $csv_fh = Tie::Handle::CSV->new( 'basic.csv',
                                     header => [qw/ name salary /] );
## print 'name' value from first line
my $csv_line = <$csv_fh>;
print $csv_line->{'name'}, "\n";

key_case

This option allows the user to specify the case used to represent the headers in hashes from line reads. By default the keys are exactly as the headers. If the value of this option is 'lower' the keys are forced to lowercase versions of the headers. If this option is 'upper' the keys are forced to uppercase versions of the headers.

my $csv_fh = Tie::Handle::CSV->new( 'basic.csv', key_case => 'lower' );
## print 'Name' value from first line using 'name' key
my $csv_line = <$csv_fh>;
print $csv_line->{'name'}, "\n";

For case-insensitive hash keys use the 'key_case' value of 'any'.

my $csv_fh = Tie::Handle::CSV->new( 'basic.csv', key_case => 'any' );
## print 'Name' value from first line
my $csv_line = <$csv_fh>;
print $csv_line->{'nAMe'}, "\n";

open_mode

If this option is defined, the value is used as the MODE argument in the 3-arg form of open. Otherwise, the file is opened using 2-arg open.

## open in read-write mode
my $csv_fh = Tie::Handle::CSV->new( 'basic.csv', open_mode => '+<' );

sep_char

Perhaps the most common reason for giving the csv_parser option is to specify a non-comma separator character. For this reason, you can specify a separator character using the sep_char option. This is passed directly to the internally created Text::CSV_XS object.

## use colon separators
my $csv_fh = Tie::Handle::CSV->new( 'basic.csv', sep_char => ':' );

If you specify both the sep_char and csv_parser options, the sep_char option is ignored.

simple_reads

This option controls whether line reads return simple hash or array references. By default this option is false, resulting in tied hashes or arrays. The tied data structures auto-stringify back to CSV format, with the hashes also having keys ordered as the header list.

When this option is true, line reads return simple hash or array references without the special tied behaviors, resulting in faster line reads.

header

The header method returns a tied array reference which, when stringified, auto-converts to a CSV formatted string of the headers. It throws a fatal exception if invoked on an object that does not have a header.

my $header = $csv_fh->header;

print $header . "\n";       ## auto-convert to CSV header string

foo($_) for @{ $header };   ## iterate over headers

AUTHOR

Daniel B. Boorstein, <danboo at cpan.org>

SEE ALSO

Text::CSV_XS

BUGS

Please report any bugs or feature requests to bug-tie-handle-csv at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Tie-Handle-CSV. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Tie::Handle::CSV

You can also look for information at:

COPYRIGHT & LICENSE

Copyright 2007 Daniel B. Boorstein, all rights reserved.

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