On Wed, 26 Aug 2009 16:41:39 +1000, Chas. Owens <chas.ow...@gmail.com> wrote:

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:

I did some searching on cpan as Uri suggested and decided on this module. Thank you very much for the code! I have some questions on the code.


#!/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) {

I changed the single pipe (|) to double pipes (||) and $token also contained empty strings. Could you explain the difference between the pipes?

        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;

Is this a commonly used method where you push empty values into an array (if $token is a , or ") and append stuff to the last array element (which is an empty string)?

}

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


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


Thanks again Chas.

--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/


--
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