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.

#!/usr/bin/perl use strict; use Text::CSV;
I knew that the text file had lines of data that I didn't need, and
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.

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 arra +y for ($x=0;$x<$elements;$x++) { print OUTFILE "$fields[$x]\t"; } } } }
Now that the files have been written to, I can close them up, and remove
the trash file

close INFILE; close OUTFILE; close TRASH; unlink $trash;
All in all, a very useful module.

In reply to Text::CSV by TStanley

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.