Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: split string by comma

by davido (Cardinal)
on Jan 11, 2012 at 00:04 UTC ( [id://947264]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://947264]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-19 22:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found