Tweet

How do I create a fixed width column file?

You want to write a file that has fixed width lines. For example, your file might need to look like this:

    Fred Flintstone          455.00       4.55
    Bart Simpson               7.45       0.07
    Roger Rabbit           1,456.99      14.57

The first column must be 20 characters long, and the second and third columns 11 characters wide (and right aligned).

The solution: use sprintf

The sprintf function allows you for format text and numbers. This is especially useful if you have variable data to write to a file.

sprintf has many options and can be a powerful formatting function. You can choose to left- or right-align text and numbers, how many decimal places to allow numbers, whether to zero-pad or space-pad numbers, and much more. The example below will produce the output above:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $filename = "test.txt";

    # A multi-dimensional array for storing the data
    my @data = (
        ['Fred Flintstone', 455, 4.55],
        ['Bart Simpson', 7.45, 0.07],
        ['Roger Rabbit', 1,456.99, 14.57],
    );

    open (FILE, ">$filename") or die "Couldn't open $filename: $!";

    foreach my $line (@data) {
        print FILE sprintf("%-20.20s%11.2f%11.2f\n", @$line);
        # or
        # print FILE sprintf("%-20.20s%11.2f%11.2f\n", $line->[0], $line->[1], $line->[2]);
    }

    close FILE;

    exit 0;

See also

perldoc -f sprintf

[Top]