Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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>) {
                if($status ==0) {
                        chomp($bad = $csv->error_input());
                        print "error: $filename($.):\n$bad\n";
        close F or die "closing $filename: $!";

Replies are listed 'Best First'.
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.

      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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://123718]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2018-02-19 00:48 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (257 votes). Check out past polls.