On Wed, Aug 26, 2009 at 02:23, Dave Tang<d.t...@imb.uq.edu.au> wrote:
> Dear list,
>
> I am trying to import entries in a csv file into a relational database,
> however there are entries such as:
>
> a,b,c,d,e,"f1,f2","g1,g2" which spoil my split(/,/).
snip

Sounds like a job for [Text::CSV][1].  Of course, you an always write
a quick parser:

#!/usr/bin/perl

use strict;
use warnings;

my $line = q/a,b,c,d,e,"f1,f2","g1,g2"/;

my $in_string;
my @rec = ("");
for my $token ($line =~ /([,"]|[^,"]+)/g) {
        if ($in_string) {
                if ($token eq q/"/) {
                        $in_string = 0;
                        push @rec, "";
                        next;
                }
        } elsif ($token eq q/,/) {
                push @rec, "";
                next;
        } elsif ($token eq q/"/) {
                $in_string = 1;
                next;
        }
        $rec[-1] .= $token;
}

print join("|", @rec), "\n";


[1] : http://search.cpan.org/dist/Text-CSV/lib/Text/CSV.pm

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to