简体   繁体   中英

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);
 };

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 (eg, 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).

Have a look at the Perl format command.

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.

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");

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"); 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM