...and, if you want to allow '"' in the fields you can extend that to:

use strict ; use warnings ; print join ",", map { if (m/[,"]/) { s/(\A|"|\n|(?<!\n)\Z)/"$1/g } ; $ +_ } split /~/ while <DATA>; __DATA__ col1~col2~col3~col4~col5 data11~data12~data13~data14~da,data15 data21~"data22"~d"ata"23~data24~da"ta"25 data31~data32~data33~data34~"data35" data,data41~data42~data43~data44~data45 data51,data52,data,junk,specialchar,sometingdata53~data54~data55
which gives:
col1,col2,col3,col4,col5
data11,data12,data13,data14,"da,data15"
data21,"""data22""","d""ata""23",data24,"da""ta""25"
data31,data32,data33,data34,"""data35"""
"data,data41",data42,data43,data44,data45
"data51,data52,data,junk,specialchar,sometingdata53",data54,data55
(the last item on each line has the line ending attached to it... so have to box a little clever to get the trailing '"' right in all cases. GrandFather used (.*), which won't match a line ending, unless you tell it to.)

Or you can just stick '"' around every item:

print join '",', map { s/(\A|"|\n)/"$1/g ; $_ } split /~/ while <DATA> +;
which is slightly more straightforward:
"col1","col2","col3","col4","col5"
"data11","data12","data13","data14","da,data15"
"data21","""data22""","d""ata""23","data24","da""ta""25"
"data31","data32","data33","data34","""data35"""
"data,data41","data42","data43","data44","data45"
"data51,data52,data,junk,specialchar,sometingdata53","data54","data55"

One assumes that you don't expect your '~' item separators to appear in any item, not even within '"' or any other escaping mechanism... The deeper you go into this kind of thing, the more you find how useful stuff on CPAN is !


In reply to Re^2: Workaround for my CSV file by gone2015
in thread Workaround for my CSV file by harishnuti

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.