I would second Japhy's suggestion to keep the perl coding simple and let the command line do more for you. But if you want to have a script stored in a file so it's always ready to repeat the operation for you whenever you need it, here's a nice balance point between scripting and command-line usage:
#!/usr/bin/perl # simple process to convert spaces and tabs to commas while ( <> ) { tr/\t /,/; print; }
So much for the perl script -- let's suppose you save that in a file called "space2comma.pl"; using the command line to handle all the file i/o for you involves a shell command like this:
space2comma.pl input.file > output.file
(I personally like making sure that the output file does not replace the input file, in case I find out that I need to fix the script or change my plan about what it's supposed to do.)

I hope you're going to be careful about getting to know the input data, and knowing what sorts of conditions the output data needs to meet. Maybe the output is supposed to have a fixed number of comma-separated fields? Maybe if the input contains some commas already, these should be treated as data (which means the fields that contain commas need to be quoted in the csv output)? Maybe if two "fields" are separated by more than one space or tab character, that whole whitespace string should be treated as a single field boundary -- so add a final "s" modifier to the "tr///" (or maybe as multiple boundaries with empty fields between them, so don't use "tr///s")?

Getting that sort of stuff wrong can be a real drag.


In reply to Re: convert txt file to csv file by graff
in thread convert txt file to csv file by aztec

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.