How do I write text in aligned columns in Perl?
Question
I am trying to write to a file from Perl. I just want to write the data in tab delimited format. However, the data that I am writing has varying lengths and is not lining up.
For example I am trying to write something like this:
Name Education Fav_Car MoneyInBank
josh High School Porche 500
SomeOtherName PHD Hyundai 50000
I just want the data to be lined up with the headers that I have on top.
I am outputting the data like so:
printf FILE ("%s%20s%20s\n", "Name", "Ed", "Car");
while (($name, $ed, $car) = $sth->fetchrow_array) {
printf FILE ("%s>>>>>>>>>>>>>%40s%40s\n", $name, $ed, $car);
};
Solution
Tab-delimited data (where the fields are not consistent in length) does not line up when opened in a text editor.
Solutions:
- Open the file in a spreadsheet.
- Open it in a word processor, select all the text, and define appropriate tab stops. (thanks, Justsalt)
- In your text editor, set your tab width to a value larger than any of your fields.
- Use spaces instead of tabs (e.g.,
printf
with field widths, or formats).
For example, you might use
printf("%-15s %-15s %-10s %9s\n", $name, $edu, $car, $cash);
The -
after the %
causes the field to be left justified. Numbers (like money) are usually right-justified (which is the default).
OTHER TIPS
Have a look at the Perl format command.
Have a look at Perl6::Form CPAN module.
This previous question/answer What Other Languages Have Features And Or Libraries Similar To Perls Format on stackoverflow may help.
In addition to way C's printf you can adjust the width dynamically with "*",
printf FILE ("%*s%*s%*s\n", 20, "Name", length($blah), "Ed", 20, "Car");
The printf does this as in C. For 20 character fields:
printf("%20s%20s%20s$20S\n",$name,$ed,$car,$money);
If you're working on Linux, an easy solution would be to use column system command, with the -t flag. just print the space separated table to a file, and just use the column command on that file.
system("column -t file > new_file");