Item Description: Manipulation routines for comma-separated values
Review Synopsis:
Author: Alan Citterman
I had a project where I needed to extract data from a file and send
it to a customer. The file in question was from a database, and it
had been exported to a CSV text file.
I would have tried to write my own regular expression to handle this,
but my overall knowledge of Perl isn't that good. However, after some
research, I found a reference to this module.
I knew that the text file had lines of data that I didn't need, and#!/usr/bin/perl use strict; use Text::CSV;
that there was an easily recognizable pattern in those lines, so I could
use a regular expression to put those lines into a trash file.
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";
Now to start reading the data from the file, store it in the $_ variable
and print it to the trash file if its not good, or parse the variable, and
print it to the output file if it is.
Now that the files have been written to, I can close them up, and removewhile (<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 arra +y for ($x=0;$x<$elements;$x++) { print OUTFILE "$fields[$x]\t"; } } } }
the trash file
All in all, a very useful module.close INFILE; close OUTFILE; close TRASH; unlink $trash;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Text::CSV
by swiftone (Curate) on Jan 11, 2001 at 02:34 UTC | |
by dilbert (Novice) on Oct 03, 2002 at 14:27 UTC | |
by AssFace (Pilgrim) on May 20, 2004 at 23:21 UTC | |
Re: Text::CSV
by dkubb (Deacon) on Jan 18, 2001 at 06:33 UTC | |
by Anonymous Monk on Apr 03, 2001 at 03:32 UTC | |
Re (tilly) 1: Text::CSV
by tilly (Archbishop) on Apr 03, 2001 at 07:53 UTC | |
Re: Text::CSV
by TStanley (Canon) on Jan 13, 2001 at 03:25 UTC | |
Re: Text::CSV
by wilmer_t (Novice) on Aug 20, 2014 at 13:33 UTC | |
by Anonymous Monk on Aug 20, 2014 at 14:32 UTC | |
by wilmer_t (Novice) on Aug 25, 2014 at 20:23 UTC |