How to printf a array without describing the format of each element?

隐身守侯 提交于 2020-05-14 18:41:05

问题


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 .

for example

@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?

something like this?

printf ("%3d\n",@array);

thanks


回答1:


Here are two approaches:

  1. Use a loop

    printf "%3d ", $_  for @array;
    print "\n";
    
  2. Use the x operator to build a variable length template

    printf "%3d " x @array . "\n", @array;
    



回答2:


Try this concoction:

print( map( {sprintf("%3d\n", $_)}, @array));


来源:https://stackoverflow.com/questions/18457175/how-to-printf-a-array-without-describing-the-format-of-each-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!