modulereview
TStanley
Author: <A HREF="alan@mfgrtl.com">Alan Citterman</A><BR>
<BR>
I had a project where I needed to extract data from a file and send<BR>
it to a customer. The file in question was from a database, and it<BR>
had been exported to a CSV text file.<BR>
<BR>
I would have tried to write my own regular expression to handle this,<BR>
but my overall knowledge of Perl isn't that good. However, after some<BR>
research, I found a reference to this module.<BR>
<BR>
<CODE>
#!/usr/bin/perl
use strict;
use Text::CSV;
</CODE>
I knew that the text file had lines of data that I didn't need, and<BR>
that there was an easily recognizable pattern in those lines, so I could<BR>
use a regular expression to put those lines into a trash file.<BR>
<BR>
<CODE>
my $input="input.csv";
my $output="output.txt";
my $trash="trashfile";
my $csv=Text::CSV->new(); #Creates a new Text::CSV object
open(INFILE,$input) || die "Can't open file $input";
open(OUTFILE,">$output") || die "Can't open file $output";
open(TRASH,">$trash") || die "Can't open file $trash";
</CODE>
<BR>
Now to start reading the data from the file, store it in the $_ variable<BR>
and print it to the trash file if its not good, or parse the variable, and<BR>
print it to the output file if it is.<BR>
<BR>
<CODE>
while (<INFILE>) {
if (/"X"/) { #The trash data has these 3 characters in it
print TRASH "$_\n";
}
else { #Now to deal with the data I want to keep
if($csv->parse($_)) { #checks to see if data exists in $_ and parses it if it does
my @fields=$csv->fields; # puts the values from each field in an array
my $elements=@fields; #gets the number of elements in the array
for ($x=0;$x<$elements;$x++) {
print OUTFILE "$fields[$x]\t";
}
}
}
}
</CODE>
Now that the files have been written to, I can close them up, and remove<BR>
the trash file<BR>
<BR>
<CODE>
close INFILE;
close OUTFILE;
close TRASH;
unlink $trash;
</CODE>
All in all, a very useful module.
Manipulation routines for comma-separated values