http://qs321.pair.com?node_id=947264


in reply to split string by comma

GrandFather is probably correct in assuming that you're dealing with run-of-the-mill CSV, and his recommendation for Text::CSV is canonical in such cases. Text::CSV_XS is another alternative if throughput is an issue.

Sometimes a picture is worth a thousand words, so I wanted to provide an example of how easy Text::CSV makes it to achieve a robust solution.

use strict; use warnings; use Text::CSV; use Data::Dumper; my @rows = ( q{1945,"4,399.00",938,1/10/2012},# Original test case. q{1945,4,399.00",938,1/10/2012}, # Missing quote intentional to te +st # behavior with malformed CSV. # Warning expected. q{1945,4,399.00,938,1/10/2012}, # A simple case (nothing quoted). q{"abc","de,f","ghi",jkl}, # Alpha with mixed quoting/commas +. ); my $csv = Text::CSV->new ( { binary => 1 } ) or die "Cannot use CSV: " . Text::CSV->error_diag; my @parsed; foreach my $row ( @rows ) { $csv->parse( $row ) or do{ # ^---- Warning results from line above when parsing bad CSV. warn "Couldn't parse [$row]: Possibly malformed CSV"; next; }; push @parsed, [ $csv->fields ]; } print Dumper \@parsed if @parsed;

Be sure to read the docs for Text::CSV prior to just dropping code from my example into place in your script. It's possible that your specific data set may require additional work such as Text::CSV configuration, data pre-processing, or result restructuring.

Update: Of course your first step is probably going to be to execute the shell command: "cpan -i Text::CSV". This will pull the module in from CPAN and install it so that it's available for use. This approach works for most Perl installations on Unix/Linux as well as Strawberry Perl on Windows. For ActivePerl you could use the ppm tool to manage your module installation.


Dave