Right justified numbers in Perl

5.5k views Asked by At

How can I print numbers right justified in Perl, like this:

a=   1
b=  22
c= 333
d=4444  
3

There are 3 answers

0
Zaid On

The official resource for this is perldoc -f sprintf , which has a nice summary of examples:

For example:

  printf '<% d>',  12;   # prints "< 12>"
  printf '<%+d>',  12;   # prints "<+12>"
  printf '<%6s>',  12;   # prints "<    12>"
  printf '<%-6s>', 12;   # prints "<12    >"
  printf '<%06s>', 12;   # prints "<000012>"
0
Mat On

Use printf with a precision and a space as "filler":

printf "a=% 4d\n", 1;
printf "b=% 4d\n", 22;
0
Pavunkumar On

Try like this.

printf ("%4d\n",1);
printf ("%4d\n",11);
printf ("%4d\n",111);
printf ("%4d\n",1111);