开发者

Perl formatting (i.e.sprintf) not retained in html display

开发者 https://www.devze.com 2022-12-08 04:04 出处:网络
I have ran into a bit of problem. Originally, I have the following input of the format: 12345apple 12orange

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&g开发者_运维百科t;</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!


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消