How to print an array without a description of the format of each element?

I want to print multiple arrays and the output element will be with a field width of 3, I think I can use printf , but if I use printf , then I need to write the format of the entire array element, but the array is large.

eg

 @array = (1,10,100,30); printf ("%3d %3d %3d %3d\n",$array[0],$array[1],$array[2],$array[3]); 

I know that I can use a loop to print an element until the whole array has passed, but I think this is not a good idea.

Is there any way that allows me to simply describe the format of an element once and then apply it to the entire array automatically?

something like that?

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

thanks

+4
source share
2 answers

Here are two approaches:

  • Use a loop

     printf "%3d ", $_ for @array; print "\n"; 
  • Use the x operator to create a variable-length pattern

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

Try this mix:

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

Source: https://habr.com/ru/post/1499069/


All Articles