使用';printf';在Perl中
我正在尝试格式化输出,使其看起来像是在列中。我正在尝试使用这个函数 以下是我所拥有的:使用';printf';在Perl中,perl,Perl,我正在尝试格式化输出,使其看起来像是在列中。我正在尝试使用这个函数 以下是我所拥有的: 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[$
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])
}
}
printf(“%s%10s%12s%10s\n”、“数量”、“说明”、“单位\$”、“总数”);
对于($he=0;$he您需要在两种格式中使用相同的数字:
printf("%3s %10s %15s %13s\n", "Qty", "Desc.", "Unit \$", "Total");
及
请注意,12.2的意思是(12位+1点+2位),这就是为什么我在第一种格式中写了15,13也是如此
还要注意,您访问数组元素的方式不正确
很久以前,Perl主要用于格式化文件,而不是使用@quantity[$he]
使用$quantity[$he]
。也就是说,将@
替换为$,它仍然具有这些功能,尽管自从Perl 4.x问世以来,我还没有在程序中使用过它
查看文档、函数和函数
我会给你一个关于代码外观的示例,除非我已经多年没有这样做了。否则,请使用printf
语句。您可以使用%-10.10s
格式类型限制文本字段的大小。这表示将字符串左对齐,并将其填充到10个字符,但不能超过10个字符
我还建议你买一本关于modernPerl的书,这本书将教你如何使用它
我已经重写了您的程序以使用引用。请注意,所有数据现在都在一个数组中,而不是分散在四个单独的数组中,您希望将索引保持在一起
我可以通过说$item[1]->{entre}
来谈论$item[1]>{entre}
的主菜。它更容易阅读和维护
还要注意的是,我已经更改了你的for
循环。在你的循环中,你必须知道你有七个项目。如果你添加了一个新项目,你必须更改你的循环。在我的循环中,我使用$#菜单
获取菜单的最后一个索引。然后我使用(0..$#菜单)
自动从0循环到@菜单中的最后一项
数组
而且,当你这么做的时候:
- 注意
printf
语句格式
- 请注意使用
use strict;
和use warnings;
。这将捕获大量错误
- 请注意我使用括号和大括号标记代码块的首选方法。这是首选方法
现在,节目:
use strict;
use warnings;
my @menu = (
{ ENTREE => "Hamburger", PRICE => 3.49, QUANTITY => 3 },
{ ENTREE => "Frankfurter", PRICE => 2.19, QUANTITY => 0 },
{ ENTREE => "French Fries", PRICE => 1.69, QUANTITY => 0 },
{ ENTREE => "Large Coke", PRICE => 1.79, QUANTITY => 4 },
{ ENTREE => "Medium Coke", PRICE => 1.59, QUANTITY => 0 },
{ ENTREE => "Small Coke", PRICE => 1.39, QUANTITY => 0 },
{ ENTREE => "Onion Rings", PRICE => 1.19, QUANTITY => 8 },
);
printf "%-3.3s %-10.10s %-6.6s %s\n\n", 'Qty', 'Desc.', 'Unit $', 'Total';
# Use $#menu to get the number of items in the array instead of knowing it's 6
foreach my $item (0..$#menu) {
# Dereference $menu[$item] to make $menu_item a hash
# This makes the syntax easier to read.
my %menu_item = %{ $menu[$item] };
if ( $menu_item{QUANTITY} ) {
printf "%3d %-10.10s %9.2f %7.2f\n",
$menu_item{QUANTITY}, $menu_item{ENTREE}, $menu_item{PRICE},
$menu_item{QUANTITY} * $menu_item{PRICE};
}
}
输出:
Qty Desc. Unit $ Total
3 Hamburger 3.49 10.47
4 Large Coke 1.79 7.16
8 Onion Ring 1.19 9.52
输出不一致。使用使用警告;
发现了4个错误!类似的情况如何?有关printf的更多信息,请参阅@quantity[$he]
的文档。应该编写$quantity[$he]
。这也不起作用。当我实现此功能时,$quantity[$he]之间只有一个空格和$selections[$he],但我希望两列匹配:(我认为这可能与@selections中的字符串长度不同有关,不管怎样?为什么不对我的$item(@menu)执行)
?在我发布我的答案几个小时后,我想到了同样的事情。我从最初的for
循环中被甩了出来,OP在那里使用了索引。这样做更好。每个$item
都是对散列的引用。
Qty Desc. Unit $ Total
3 Hamburger 3.49 10.47
4 Large Coke 1.79 7.16
8 Onion Ring 1.19 9.52