Perl Question

Hi ,

I have a file that looks like this:

24.999
4.987
34.987
3.900
97.334

My Question:
How i can right aligment in perl the number to look like this:

24.999
 4.987
34.987
 3.900
97.334

I need code using sprintf or printf or format.

I am new to perl and I am not getting it reading perldoc ...i am lost.

Please provide help will be appreciated

thanks,

Don't even treat them like numbers:

printf( "%6s", $number );

another way:

while(<DATA>){
   my $t = sprintf("%6.3f",$_); 
   print $t,"\n";
}
__DATA__
24.999
4.987
34.987
3.900
97.334

Using the %f template treats the values as floating point numbers so if you do something like this:

while(<DATA>){
   my $t = sprintf("%6.2f",$_); 
   print $t,"\n";
}
__DATA__
24.999
4.987
34.987
3.900
97.334

the value of the number can change due to rounding off. If all you really want to do is right-justify, the %s template BMDan suggests might be more appropriate.

perl -ne 'if($.==1){$len=length($_);} printf("%${len}s",$_);' file

Thats the best suggestion I"ve ever seen you post summer_cherry. It does assume that the first line of the file should be used to set the width of all the rest of the lines, but sometimes we do have to make assumptions when posting suggestions.

Thanks for everyone reply.

I am sorry for replying little late.

Here is part of perl code that i want to print out.

 print ("------------------------------------------------------","\n");
  printf "%+2sSELECTION\t%+3sVOTES\t%+3sPERCENTAGE\n";
  print ("------------------------------------------------------","\n");

  printf("Choice 1\t %6s $count\t\t %6s $iRoundup1 \n");
  printf("Choice 2\t %6s $count\t\t %6s $iRoundup2 \n");
  printf("Choice 3\t %6s $count\t\t %6s $iRoundup3 \n");

  #printf "%1s", Choice 1\t,"%6s",$count\t\t,"%6s",$iRoundup1\n";
  #printf "%1s", Choice 2\t,"%6s",$count2\t\t,"%6s",$iRoundup2\n";
  #printf "%1s", Choice 3\t,"%6s",$count3\t\t,"%6s",$iRoundup3\n";
  print ("------------------------------------------------------", "\n");

so basically i want to print numbers right alignment.

I tried DMan printf("%6s", $number) but it didn't worked.

Or
May be i am doing something wrong.

Can some help me and fix the printf so it print number right align.

thank you for your time
-Lalit

Fixed it for you. Enjoy.

You also want to break out SELECTION VOTES PERCENTAGE in the same way.

printf "%+2s\t%+3s\t%+3s\n", qw(SELECTION VOTES PERCENTAGE);

The widths probably have to be adjusted but you get the idea, I hope.

With use warnings you would get an error message (albeit a somewhat misleading one) for using printf with too few parameters. For backwards-compatibility reasons, Perl is woefully silent by default. You want to get into the habit of adding use strict; use warnings; to all of your scripts.