views:

158

answers:

3

I have ran into a bit of problem. Originally, I have the following input of the format:

12345     apple
12     orange

I saved the first column as $num and second column as $fruit. I want the output to look like this (see below). I would like for the output to align as if the $num are of all the same length. In reality, the $num will consists of variable-length numbers.

12345     apple
12        orange

As suggested, I use the following code:

$line = sprintf "%--10s %-20s", $num, $fruit;

This solution works great in command-line display, but this formatting is not retained when I try to display this via HTML. For example..

print "<html><head></head><body>
        $line
        </body></html>";

This produces the same output as the original before formatting. Do you guys have a suggestion as to how I can retain the sprintf formatting in html web-based display? I try to pad the $num with whitespaces, but the following code doesn't seem to work for me.

$num .= (" " x (10 - length($num)));

Anyways, I would appreciate any suggestions. Thanks!

+11  A: 

HTML ignores extra whitespace. And the fact that it's probably displaying with a proportional font means it wouldn't line up even if the extra spaces were there.

The easy option is to just surround the text with <pre> tags, which will display by default with a monospace font and whitespace preserved. Alternatively, you can have your code generate an HTML table.

friedo
Using <pre> works for me! thank you friedo. I'm learning so much from the SO community. thanks again.
qdog
+4  A: 

HTML compresses all consecutive spaces down to one space. If you want your output to be lined up like a table, you have to actually put the values in an HTML table.

Ron

Ron Savage
+2  A: 

The 'pre' in <pre> means preformatted, which exactly describes the output of a sprintf() statement. Hence the suggestion from friedo and I suspect, others.

pavium