By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,710 Members | 1,906 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,710 IT Pros & Developers. It's quick & easy.

How to substitute the space for field of csv format?

P: 13
Currently my data is this in excel but as a csv format:

"a", "as " sd", "123"
"b","asd","234"
"c","as d","345"

I wanted to make the output this:
a,as " sd,123
b,asd,234
c,as d,345

the code i tried is this

Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use Text::CSV_XS;
  3.  
  4. my $csv = Text::CSV_XS->new({'allow_whitespace'=>1,'allow_loose_quotes'=>1});
  5. my $file = "test.csv";
  6.  
  7. open(DAT, $file) || die("Cannot Open File");
  8.  
  9. while (<DAT>) {
  10.     $csv->parse($_);
  11.     my @fields = $csv->fields();
  12.     foreach ("@fields")
  13.     {
  14.         $_ =~ s/ +/,/;
  15.         print "$_\n";
  16.     }
  17. }
  18.  
How can i modify to get what I desired?
Aug 14 '08 #1
Share this Question
Share on Google+
1 Reply


P: 14
In your code at line number 14. You need to use \s+ for one or more space character.
so it will be
Expand|Select|Wrap|Line Numbers
  1. $_ =~ s/\s+/,/;
Hope this works
Aug 15 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.