styris
styris

Reputation:

How do I write text in aligned columns in Perl?

I am trying to write to a file from Perl. I just want to write the data in a 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 the 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);
 };

Upvotes: 20

Views: 59185

Answers (6)

Mattan
Mattan

Reputation: 753

If you're working on Linux, an easy solution would be to use the 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"); 

Upvotes: 1

Adam Flott
Adam Flott

Reputation: 487

In addition to the way like C's printf, you can adjust the width dynamically with "*",

printf FILE ("%*s%*s%*s\n", 20, "Name", length($blah), "Ed", 20, "Car");

Upvotes: 2

draegtun
draegtun

Reputation: 22560

Have a look at the Perl6::Form CPAN module.

The previous question/answer What Other Languages Have Features And Or Libraries Similar To Perls Format on Stack Overflow may help.

Upvotes: 4

Brian Carlton
Brian Carlton

Reputation: 7763

The printf function does this as in C. For 20 character fields:

printf("%20s%20s%20s$20S\n", $name, $ed, $car, $money);

Upvotes: 1

cjm
cjm

Reputation: 62099

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).

Upvotes: 29

Paul Tomblin
Paul Tomblin

Reputation: 182782

Have a look at the Perl format command.

Upvotes: 6

Related Questions