Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Parse/Verify CSV files

by coolmichael (Deacon)
on Nov 07, 2001 at 02:51 UTC ( #123718=snippet: print w/ replies, xml ) Need Help??

Description: CSV has very specific requirements. This simple snippet will parse the CSV file, and report any lines that would generate errors with DBD::CSV. Currently, it uses Text::CSV, but you could change it to Text::xSV or Text::CSV_XS fairly easily. specify filenames on the command line, as such: ./vfycsv FILENAME FILENAME2

update 11/06/01: added close line.

#!/usr/bin/perl -w
use strict;

use Text::CSV;

my $csv=Text::CSV->new();
my $line;
my $status;
my $bad;
my $filename;

while($filename = shift @ARGV) {
        open F, $filename or die "opening filename: $!\n";

        while($line=<F>) {
                $status=$csv->parse($line);
                if($status ==0) {
                        chomp($bad = $csv->error_input());
                        print "error: $filename($.):\n$bad\n";
                }
        }
        close F or die "closing $filename: $!";
}

Comment on Parse/Verify CSV files
Download Code
Re: Parse/Verify CSV files
by Armos (Scribe) on Nov 07, 2001 at 04:19 UTC
    I only glanced at the code and maybe I missed something, but don't forget to close F after the end of your inner loop.

    -A
      There is no need to close filehandles, Perl will do it for you. It is good style to localize them ahead of time though.

      A far worse error is putting the return in the die statement. When you do that you tell Perl that you are doing all of the formatting of that message. If you simply leave it out then the person fixing your code gets the very handy information of what file and line number the error came from. This kind of context can really speed up debugging a complex program.

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://123718]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (14)
As of 2014-09-01 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (300 votes), past polls