in reply to Convert CSV file to TAB delimited

"perl -e ' $sep=","; while(<>) { s/\Q$sep\E/\t/g; print $_; } warn "Ch +anged $sep to tab on $. lines\n" ' csvfile.csv > tabfile.tab"
becomes
#!/usr/bin/perl use strict; use warnings; my $sep=","; open (my $csv_file , "<" , 'csvfile.csv'); open (my $tab_file , ">" , 'tabfile.tab'); while(<$csv_file>) { s/\Q$sep\E/\t/g; print $tab_file, $_; } warn "Changed $sep to tab on $. lines\n"
However what do you do with lines such as
"Monster, The Cookie", "123 Sesame St, TV land"
When processing CSV's there are all kinds of edge cases, so use a module that has looked at these issues already rather than ending up with unsupportable code, I would suggest Text::CSV.

You can open a new csv object with a different separator and just write it without having to contemplate cases like the above.

print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."

Replies are listed 'Best First'.
Re^2: Convert CSV file to TAB delimited
by TCM (Acolyte) on Sep 23, 2010 at 13:27 UTC
    Thank you for the code Utilitarian! 'tabfile.tab' is created, but it's empty. I ran the script through debug and when I look at $_, I see the data in tab format. Why is 'tabfile.tab' empty though?

      Because of a small error: one comma too many :)

      while (<$csv_file>) { s/\Q$sep\E/\t/g; print $tab_file, $_; # ^- That comma should not be there }

      Other than that, I still think you ought to look into the proposed Text::CSV_XS or Text::CSV solutions.


      Enjoy, Have FUN! H.Merijn
        Thank you all for taking the time to reply to my question, I really appreciate it!! Removing the comma where Tux had indicated did the trick. I don't think I would have ever figured that one out... Once again, thank you all for your time TCM