in reply to Re: split on comma-separated fields, where a field may have commas inside quotes
in thread split on comma-separated fields, where a field may have commas inside quotes

Don't split, collect.

I like that; I'll try to remember it.

But the first asterisk yields empty chunks; fixed with a plus:

@chunks = $str =~ /[^,"]+(?:"[^"]*"[^,"]*)*/g;
  • Comment on Re^2: split on comma-separated fields, where a field may have commas inside quotes
  • Download Code

Replies are listed 'Best First'.
Re^3: split on comma-separated fields, where a field may have commas inside quotes
by JavaFan (Canon) on Jun 10, 2009 at 14:28 UTC
    Putting a + there instead of a * means that
    "foo","bar"
    is split into a single element:
    foo","bar
    which is highly unlikely to be wanted.
Re^3: split on comma-separated fields, where a field may have commas inside quotes
by CountZero (Bishop) on Jun 10, 2009 at 18:33 UTC
    But the first asterisk yields empty chunks
    grep will solve that problem easily:
    @chunks = grep {$_} ($str =~ /[^,"]*(?:"[^"]*"[^,"]*)*/g);

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James