在 Perl 中使用“printf"格式化输出 [英] Formatting output with 'printf' in Perl

查看:372
本文介绍了在 Perl 中使用“printf"格式化输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化我的输出,使其看起来像是在列中.我正在尝试使用 printf 函数.

I'm trying to format my output to look like it's in columns. I'm trying to use the printf function.

这是我所拥有的:

printf("%s %10s %12s %10s\n", "Qty", "Desc.", "Unit \$", "Total");

for ($he = 0; $he <= 6; $he++) {
    if (@quantity[$he] != 0) {
        printf("%d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he] * @quantity[$he])
    }
}

我试图使 for 循环的 if 语句中的第二个 printf 与数量"、描述"对齐.、单位\$"和总计".

I'm trying to make it so that the second printf inside of the if statement of the for loop lines up with the "Qty", "Desc.", "Unit \$" and "Total."

推荐答案

您需要在两种格式中使用相同的数字:

You need to use the same numbers in the two formats:

printf("%3s %10s %15s %13s\n", "Qty", "Desc.", "Unit \$", "Total");

printf("%3d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he]*@quantity[$he])

注意12.2的意思是(12位+1点+2位),这就是我用第一种格式写15的原因.13号也是一样.

Note that 12.2 means (12 digits + 1 point + 2 digits), which is why I wrote 15 in the first format. The same goes for the 13.

另请注意,您访问的数组元素不正确.

Also note that you're accessing array elements incorrectly.

使用 $quantity[$he] 代替 @quantity[$he].也就是说,将 @ 替换为 $.

Instead of @quantity[$he] use $quantity[$he]. That is, replace the @ with a $.

这篇关于在 Perl 中使用“printf"格式化输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆