The "Perl Cookbook" is very cool! But some examples can and must be optimized :^) . This is my optimization for "parse_csv()", from page 56.
#!/usr/bin/perl # # variant from Cookbook # sub parse_csv { my $text = shift; my @new = (); push (@new, $+) while $text =~ m{ "([^\"\\]*(?:\\.[^\"\\]*)*)",? | ([^,]+),? | , }gx; push (@new, undef) if substr($text, -1, 1) eq ","; return @new; } # # second variant from Cookbook # (not interesting - nothing to optimize) ;-) # sub parse_csv2 { use Text::ParseWords; return quotewords(",",0,$_[0]); } # # my variant # sub parse_csv3 { local $_ = $_[0]; s/\"(.*?)(?<!\\)\",?|([^,]+),?|(?<=,),?/push @res,"$1$2"/ge; return @res; } # # Tests # $line = q<XYZZY,"","O'Reilly, Inc",,,"Wall, Larry","a \"glug\" bit,",5 +,"Error, Core Dumped">; @fields = parse_csv3($line); for ($i = 0; $i < @fields; $i++) { print "$i : $fields[$i]\n"; }

Replies are listed 'Best First'.
Re: parse_csv (Cookbook)
by xaphod (Monk) on Sep 28, 2004 at 16:18 UTC
    Fine... except that stuff like "19"" rackmount" will be parsed as 2 fields, not 1.
    --
    TTFN, FNORD

    xaphod
      Which is identical behaviour to parse_csv - so it's a good replacement for the other code - which is what powerman set out to do... :-)

      Unfortunately even Text::ParseWords seems to have its problems handling CSV... if you have for example:

      q<"19"" rackmount",more data>
      Instead of converting
      "19"" rackmount"
      to
      19" rackmount
      Which is what I understand it should do (try saving it in a CSV file and opening it in excel) It converts it to
      19 rackmount
      - losing the " altogether :-(

      Either we are not using Text::ParseWords the right way, or it can't cope with CSV :-(

        Im not sure if its correct to consider Excel-CSV to be "CSV". I personally don't consider them equivelent.

        ---
        $world=~s/war/peace/g