Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to parse csv file using Text::CSV

Tags:

perl

I've the csv file in this format:

"Keyword"   "Competition"   "Global Monthly Searches"   "Local Monthly Searches (United States)"    "Approximate CPC (Search) - INR"

"kasperaky support" -0  -0  -0  -0

The first line is the column titles.

I've tried most of options in Text::CSV but I'm not able to extract the fields.

Here sep_char=>' '

The nearest I could go is to get the first word of the first column("kasperaky" only).

I'm creating the object this way(while trying various settings):

my $csv = Text::CSV->new ( { 
    binary => 1 ,
    sep_char=>' ',allow_loose_quotes=>0,quote_space=>0,quote_char          => '"',
    ,allow_whitespace    =>0, eol=>"\015\012"
     } ) 
                 or die "Cannot use CSV: ".Text::CSV->error_diag ();
like image 238
AgA Avatar asked Sep 18 '26 07:09

AgA


2 Answers

Your CSV is tab-separated. Use the following (code is tested to work against your example file):

use strictures;
use autodie qw(:all);       # automatic error checking open/close
use charnames qw(:full);    # \N named characters
use Text::CSV qw();
my $csv = Text::CSV->new({
    auto_diag   => 2,       # automatic error checking CSV methods
    binary      => 1,
    eol         => "\N{CR}\N{LF}",
    sep_char    => "\N{TAB}",
}) or die 'Cannot use CSV: ' . Text::CSV->error_diag;

open my $fh, '<:encoding(ASCII)', 'computer crash.csv';
while (my $row = $csv->getline($fh)) {
    ...
}
close $fh;
like image 61
Zaid Avatar answered Sep 21 '26 07:09

Zaid


To call that a CSV file is a bit of stretch! Your separator isn't a space, it's a sequence of 1 or more spaces, and Text::CSV doesn't handle that. (allow_whitespace doesn't work when your separator is a space, unfortunately.) You could use something like:

use List::MoreUtils qw( apply );
my @fields = apply { s/\\(.)/$1/sg } $line =~ /"((?:[^"\\]|\\.)*)"/sg;

Now, if those are tabs, that's a different story, and you could use sep_char => "\t".

like image 29
ikegami Avatar answered Sep 21 '26 07:09

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!