Perl formatting (like sprintf) is not saved in html display

I have a problem. Initially I have the following format input:

12345     apple
12     orange

      

I saved the first column as $ num and the second column as $ fruit. I want the result to look like this (see below). I would like the output to be aligned as if the $ num are the same length. In reality, $ num will be variable length numbers.

12345     apple
12        orange

      

As suggested, I am using the following code:

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

      

This solution works fine in command line mode, but this formatting is not preserved 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 have any suggestion as to how I can keep the sprintf formatting in the html web display? I'm trying to pad out $ num with spaces, but the following code doesn't seem to work for me.

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

      

Anyway, I would appreciate any suggestions. Thank!

+2


source to share


3 answers


HTML ignores extra spaces. And the fact that it is probably displayed with a proportional font means it doesn't line up even if there were extra spaces in there.



An easy option is to simply surround the text with <pre> tags, which will be displayed by default, keeping the monospaced font and white space. Alternatively, you can create HTML table code.

+11


source


HTML compresses all sequential spaces to a single space. If you want your output to be aligned like a table, you must actually put the values ​​into an HTML table.



+4


source


"pre" in <pre>

stands for preformatted, which accurately describes the output of the statement sprintf()

. Hence, speculation from Frido and I suspect others.

+3


source







All Articles