in reply to Re: Code for elegance, code for clarity
in thread Code for elegance, code for clarity
And for the OP, I think that reversing a Boolean is better expressed as $quoted = !$quoted rather than $quoted = 1 - $quoted.
There's no need to be destructive with s///; all you need is to walk the pattern with //g, and there's no need to special-case the empty quotes. More efficiency can be gained by reading strings of non-quote, non-comma characters. The code becomes very clear, though the regex is a little complicated.
sub csv_split { local $_ = shift || return undef; my @array = (); my $count = my $quoted = 0; while ( /([^,"]+|[,"])/g ) { if ($1 eq ',' and !$quoted) { $count++; } elsif ($1 eq '"') { $quoted = !$quoted; } else { $array[$count] .= $1 } } @array; }
|
---|