fixedwidthfile

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:

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:

See also

perldoc -f sprintf

Scroll to Top