SineSwiper has asked for the wisdom of the Perl Monks concerning the following question:
&read_csv; sub read_csv { my @csv_lines = ('begin,middle,end'."\n", '"This is a ""test""",middle,end'."\n", '"""test"""", asd",middle,end'."\n", '""","""",""",","",",end'."\n", '"Multi-'."\n", 'line",middle,end'."\n"); my $prev_line; foreach my $line (@csv_lines) { # Normally, this would be a while( +my $line = <CSV>) loop print "CSVL: $line"; $line =~ s/[\0\r]//g; $line = $prev_line.$line; # Parse quoted stuff while ($line =~ /(?<!\")(\")((?:\"\"|[^\"]+)+?)(\"|\n)(?!\")/g +cs) { my ($endpos, $starter, $token, $ender) = (pos($line), $1, +$2, $3); my $oldlen = length($starter.$token.$ender); my $startpos = $endpos - $oldlen; print "Token: $token ==> "; $token =~ s/\"\"/\0QUOTE\0/g; $token =~ s/,/\0COMMA\0/g; $token =~ s/\n/\0NEWLINE\0/g; $ender =~ s/\n/\0NEWLINE\0/g; print "$token\n"; substr($line, $startpos, $oldlen, ($starter.$token.$ender) +); pos($line) = $endpos + (length($starter.$token.$ender) - $ +oldlen); print "Line: $line\n"; } # Runaway multi-line; grab the next line and try it again if ($line =~ /\0NEWLINE\0$/) { $prev_line = $line; next; } undef $prev_line; $line =~ s/[\"\n]//g; # Remove non-data # Re-translate masked characters my @values = split(/,/, $line); foreach $value (@values) { $value =~ s/\0QUOTE\0/\"/g; $value =~ s/\0COMMA\0/\,/g; #$value =~ s/\0NEWLINE\0/\n/g; $value =~ s/\0NEWLINE\0/\\n/g; # for testing, use literal '\ +n' } print "Values: ".join(' | ', @values)."\n"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Successful CSV reader?
by Limbic~Region (Chancellor) on Apr 26, 2005 at 12:33 UTC | |
by jZed (Prior) on Apr 26, 2005 at 15:51 UTC | |
by tilly (Archbishop) on Apr 27, 2005 at 21:18 UTC | |
by jZed (Prior) on Apr 27, 2005 at 21:35 UTC | |
by Limbic~Region (Chancellor) on Apr 26, 2005 at 17:13 UTC | |
by jZed (Prior) on Apr 26, 2005 at 17:23 UTC | |
|
Re: Successful CSV reader?
by salva (Canon) on Apr 26, 2005 at 09:16 UTC | |
by SineSwiper (Beadle) on Apr 26, 2005 at 10:08 UTC | |
by salva (Canon) on Apr 26, 2005 at 11:07 UTC | |
|
Re: Successful CSV reader?
by dragonchild (Archbishop) on Apr 26, 2005 at 12:59 UTC | |
by SineSwiper (Beadle) on Apr 27, 2005 at 10:59 UTC |