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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.