Using Text::CSV or the faster Text::CSV_XS (which is automatically used by Text::CSV if installed), you prepare yourself for more complicated CSV files. Your example isn't that hard to parse, but once escapes, binary or embedded newlines come in to play, you are doomed when using regular expressions. FWIW, Text::CSV::Simple uses Text::CSV_XS for parsing too.

As a bonus you get an even faster parsing with this dedicated module. I've created (using your example) a file with 5000 records, and then ran

use strict; use warnings; use autodie; use Benchmark qw( cmpthese ); use Text::CSV_XS; my $file = "sample.csv"; my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 }); cmpthese (10, { regex => sub { open my $fh, "<", $file; while (<$fh>) { my @s = map {s/[",]//g;$_}(split /,(?!(?:[^",]+",))/,$_)[0 +,8]; } }, csv_xs => sub { open my $fh, "<", $file; while (my $row = $csv->getline ($fh)) { my @s = @{$row}[0,8]; } }, });

Which, IMHO, is nor only faster, but also easier in maintenance. The result:

Rate regex csv_xs regex 6.29/s -- -20% csv_xs 7.87/s 25% --

Enjoy, Have FUN! H.Merijn

In reply to Re: Extracting fields from CSV by Tux
in thread Extracting fields from CSV by suhailck

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.