问题
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:
Use a loop
printf "%3d ", $_ for @array; print "\n";
Use the
x
operator to build a variable length templateprintf "%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