tags:

views:

1182

answers:

5

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);
 };
+9  A: 

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

cjm
Or open it in a word processor and define appropriate tab stops.
Justsalt
+3  A: 

Have a look at the Perl format command.

Paul Tomblin
I wouldn't use format for any new projects, use Perl6::Form instead.
Brad Gilbert
+1  A: 

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

printf("%20s%20s%20s$20S\n",$name,$ed,$car,$money);
Brian Carlton
Do those need to be %-20 to left justify?
Daniel LeCheminant
how can i make them left justified?
@styris: See Daniel L's comment on this very question!
j_random_hacker
+3  A: 

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.

/I3az/

draegtun
+1  A: 

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