如何在不描述每个元素格式的情况下打印数组? [英] How to printf a array without describing the format of each element?
问题描述
我想打印几个数组,输出的元素的字段宽度为3,我想我可以使用 printf
,但是如果我使用 printf
然后我需要写出array的所有元素的格式,但是数组很大。
I want to print several arrays and the element of output will with field width 3 , I think I can use printf
, but if I use printf
then I need to write the format of all element of array , but the array is big .
例如
@array = (1,10,100,30);
printf ("%3d %3d %3d %3d\n",$array[0],$array[1],$array[2],$array[3]);
我知道我可以使用循环来打印元素,直到所有数组循环通过为止,但是我认为不是一个好主意。
I know I can use loop to print a element until all the array loop through , but I think it's not a good idea .
有没有一种方法可以让我一次描述元素的格式,然后自动应用于整个数组?
Does there exists any way can let me just describe the format of element one time , then apply to the whole array automatically?
像这样吗?
printf ("%3d\n",@array);
谢谢
推荐答案
有两种方法:
-
使用循环
Use a loop
printf "%3d ", $_ for @array;
print "\n";
使用 x
运算符建立一个可变长度的模板
Use the x
operator to build a variable length template
printf "%3d " x @array . "\n", @array;
这篇关于如何在不描述每个元素格式的情况下打印数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!