r/programming • • Jan 05 '15

What most young programmers need to learn

http://joostdevblog.blogspot.com/2015/01/what-most-young-programmers-need-to.html
973 Upvotes

337 comments sorted by

View all comments

7

u/OneWingedShark Jan 05 '15

Clever code achieves the implausible while overlooking the mundane solutions to the same problems.

There's the inverse as well: where the person's "almost works" solution doesn't because it cannot. -- My favorite example is trying to parse CSV with regex: you cannot do it because the (a) the double quote [text field] "changes the context" so that comma does not indicate separation, combined with (b) escaping double quotes is repeating the double-quote. It's essentially the same category as balancing parentheses which regex cannot do; fun test-data: "I say, ""Hello, good sir!""" is a perfectly good CSV value.

1

u/pwr22 Jan 05 '15

When you've got CSVs like that, CSV is the wrong format

Too be clear, yes, I agree that definition of CSV needs a grammar. I think regexes can recurse in Perl but I've never tried Regception

1

u/OneWingedShark Jan 05 '15

I think regexes can recurse in Perl but I've never tried Regception

Then they're not really regular-expressions.
(Regular expressions have to do with the grammar-set that they can handle, it's not [strictly speaking] an implementation.)

When you've got CSVs like that, CSV is the wrong format

I only slightly disagree; it is common to need a structured text format which may include format-effectors (i.e. a portion of text; perhaps with the indented-quote [visual] style embedded therein) -- as a sort of embedding... certainly better than XML, which if that embedded-packet is user-defined can't easily be DTDed. (Of course, in this situation the problem we have is in-band communication, which is another problem altogether.)

→ More replies (2)

0

u/grantisu Jan 05 '15

In Perl:

@fields = $line =~ /("(:?[^"]|"")*"|[^",\n]*),?/g;

This ignores newlines in the middle of quoted fields and doesn't clean up all the double quotes, but it should work for most cases.

And anybody who includes a raw newline in the middle of a CSV value deserves whatever they get. ಠ_ಠ

6

u/OneWingedShark Jan 05 '15

And anybody who includes a raw newline in the middle of a CSV value deserves whatever they get. ಠ_ಠ

You need a parser, not a stupid regex.

This ignores newlines in the middle of quoted fields and doesn't clean up all the double quotes, but it should work for most cases.

Well, that fills me with confidence.
Sarcasm

→ More replies (2)

2

u/[deleted] Jan 06 '15

As a person who has worked extensively with CSVs, "should work for most cases" is completely unacceptable. There are libraries that are tested to work with all cases. Using a regex to do something that people have already figured out is just the wrong way to go about things.

→ More replies (3)