Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Parse comma separated data (See related posts)

Import data in CSV format. Normally an easy task using split but sometimes, the fields will have comma's enclosed by quotes.
Something like.
Aaron, "123 Main St, USA", 555-555-1212
Assuming your string gets put into $text.
    my @new  = ();
    push(@new, $+) while $text =~ m{
        # the first part groups the phrase inside the quotes.
        # see explanation of this pattern in MRE
        "([^\"\\]*(?:\\.[^\"\\]*)*)",?
           |  ([^,]+),?
           | ,
       }gx;
       push(@new, undef) if substr($text, -1,1) eq ',';

Taken from Jeffrey Friedl's Mastering Regular Expressions

You need to create an account or log in to post comments to this site.


Related Posts