Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 310
user2131116 Avatar asked Aug 27 '13 04:08

user2131116


People also ask

How do you print an array format?

Print an Array Using Arrays. toString() and Arrays. deepToString() The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.

How do I print an array of strings?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.


1 Answers

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;
    
like image 175
mob Avatar answered Oct 25 '22 16:10

mob