#!/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 | |
by serf (Chaplain) on Nov 15, 2004 at 19:13 UTC | |
by demerphq (Chancellor) on Aug 30, 2005 at 12:27 UTC | |
by serf (Chaplain) on Aug 30, 2005 at 14:48 UTC | |
by jZed (Prior) on Aug 30, 2005 at 15:09 UTC |