Why would I use Tie::Array::CSV?

After (IMO) elegantly solving an SO question using my Tie::Array::CSV, I thought I might share it here to give you all an idea of when you might want to use it. This example is only reading the file, but remember that T::A::CSV gives you full row/column read/write access to the underlying CSV file in place.

The OP needed to find the column with a certain identifier which was 7 chars starting with a letter (in the example data below, this is the fouth column (i.e. index 3)). Then extract the number of repetitions of that identified in that column. Here was the solution that I posted.

#!/usr/bin/env perl

use strict;
use warnings;

use File::Temp;
use Tie::Array::CSV;
use List::MoreUtils qw/first_index/;
use Data::Dumper;

# this builds a temporary file from DATA
# normally you would just make $file the filename
my $file = File::Temp->new;
print $file <DATA>;
#########

tie my @csv, 'Tie::Array::CSV', $file;

#find column from data in first row
my $colnum = first_index { /^\w.{6}$/ } @{$csv[0]};
print "Using column: $colnum\n";

#extract that column
my @column = map { $csv[$_][$colnum] } (0..$#csv);

#build a hash of repetitions
my %reps;
$reps{$_}++ for @column;

print Dumper \%reps;

__DATA__
"ABCDEFGHIJK05","site","date1","ab96abc","date2"
"ABCDEFGHIJK05","site","date2","ab96abc","date2"
"ABCDEFGHIJK05","site","date1","cd98abc","date2"

(The OP gave one line of data, so I puffed it to 3, also to play blogs.perl.org’s width restrictions the data given here is rewritten. See the original post for the full stuff if you must.)

Of course I know you can do this with Text::CSV directly, but I like that it lets me think in terms of columns rather than objects and parsers and accessors.

4 Comments

Should this

my @column = map { $csv[$_][$colnum] } (0..$#csv);

not actually be written like this?

my @column = map { $csv[$_][$colnum] } (0..@csv);

No, it should not. Sorry for the confusion, you may well delete my comments, if you want to.

Watch out though - CSV is ultimately cursed by not having a standard character set so interop will eventually lead to UTF-8/UTF-16/Latin 1 horrors.

Leave a comment

About Joel Berger

user-pic As I delve into the deeper Perl magic I like to share what I can.