Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need help. I need to convert a comma delimited file to fixed length format. I'm new to this and have no idea where to start. I have feeling the know how is here among the Wise Ones of Perl. Much thanks in advance!!!

Replies are listed 'Best First'.
Re: Seeking fixed length
by jeroenes (Priest) on Jul 05, 2001 at 22:01 UTC
    There is more to comma-delimiting than meets the eye. See Text::xSV and DBD::CSV. But in general:
    while( <> ){ split /,/; print pack 'A10'x (scalar @_), @_; }
    Run it as perl convert.pl <input.txt >output.txt

    See the docs for while, split and pack. You can accomplish similar things with sprintf (as pack stuff is pretty complicated if you're not used to perl). You might wanna check perldata and perlvar as well.

    Hope this helps,

    Jeroen
    "We are not alone"(FZ)
    Updated, typo fixed thanks particle.

Re: Seeking fixed length
by VSarkiss (Monsignor) on Jul 05, 2001 at 22:18 UTC
    Yes, the people who frequent the monastery know Perl and have ESP as well. ;-)

    OK, taking a great leap, here's what I would suggest:

    • Get and install the Text::CSV module to read in the file. If you attempt to write your own csv-separator you will probably not handle embedded commas and strings correctly. Also, merlyn, who has more ESP than others, will find you and smite you heavily for re-inventing wheels.
    • Use printf with fixed sizes to output records. That is, every specifier in your format should be preceded with a length.
    Your basic algorithm then will be to open both files, then enter a loop where you read a line into an array, then write it out with fixed sizes.

    To mis-quote Tom Christiansen: this reply may be somewhat sub-serious, but when you ask a vague question, you should expect a bit of whimsy.

    HTH

Re: Seeking fixed length
by Hofmator (Curate) on Jul 06, 2001 at 14:51 UTC

    An important addition to the use of (s)printf because it is not used everyday (but you can read it in the excellent tutorial Using (s)printf() by reptile). In order to enforce a field width of e.g. 3 for a string you have to use:

    printf "%3.3s\n", 'Ho'; printf "%3.3s\n", 'Hogfather' printf "%3s\n", 'Hogfather'; # this prints Ho Hog Hogfather
    Just using %3s does not enforce the maximum length of the field - and btw pack doesn't have these 'problems'.

    Update: Of course maybe it's not such a good idea to silently throw away part of the fields - so you should check the length of them beforehand. But this depends on your purpose ...

    -- Hofmator