I've written a CSV reader, which I think should handle every case of quoting pairs, etc. It will remove NULL and LINEFEED characters, but other than that, it should be a completely compliant CSV reader. I just want to know if there's a case where this wouldn't work:
&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"; } }

In reply to Successful CSV reader? by SineSwiper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.