in reply to Extracting fields from CSV
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% --
|
|---|