in reply to Converting CSV files to fixed width flat files

See Text::CSV. Works well to read or write CSV (you usually can't just split on commas).

The perl builtin sprintf should be just fine for building fixed-width fields, or printf to build and print in one step.

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: Converting CSV files to fixed width flat files
by Limbic~Region (Chancellor) on May 27, 2003 at 19:58 UTC
    halley,
    Just to extend your very correct comment a little further:
    #!/usr/bin/perl -w use strict; use Text::CSV; my $csv = Text::CSV->new; open (INPUT,"input.txt") or die "\nCan't open input.txt for reading : +$!\n"; open (OUTPUT,">output.txt") or die "\nCan't open output.txt for writin +g : $!\n"; select OUTPUT; while (<INPUT>) { $csv->parse($_); my @IF = $csv->fields(); foreach my $element (@IF) { #printf command goes here } print "\n"; }
    Of course printf may truncate fields that are too short long and there are more programmer efficient ways to do the printf. I was just using this syntax for readability purposes.

    Cheers - L~R

      To the best of my knowledge, printf (and sprintf) will never truncate a field that is too long for the width specified in the format string -- it will always provide each field with as many characters as needed to fit a given string with "%s" or all digits with "%d", or all digits to the left of the decimal point with "%f", thereby screwing up the programmer's intended vertical alignment of fields on successive lines, rather than eliminate significant data that would not have fit the programmer's margins.

      update: thanks to PodMaster for some much needed tutoring... my comments above did not consider format specs that really do impose field truncation, like "%1.1s" -- I was only thinking of the more common flavor, like "%1s", which does not truncate. (I still don't know how to truncate numerics...)

        To the best of my knowledge, printf (and sprintf) will never truncate a field that is too long for the width specified in the format string
        s?printf does what you tell it  printf "%1.1s$/", 'foy'; yields 'f',  printf "%s$/", 'foy'; yields 'foy'. As for Limbic~Regions note, you can't convert variable width "records" to fixed width ones without possibly undergoing some truncation ;)


        MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
        I run a Win32 PPM repository for perl 5.6x+5.8x. I take requests.
        ** The Third rule of perl club is a statement of fact: pod is sexy.