Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to have a formatted output with Perl

I want to output strings into eight columns, but I want to keep the spacing the same. I don't want to do it in HTML, but I am not sure how to do it normally. Example:

Something    Something     Something     Something     Something
Else         Else          Else          Else          Else
Another      Another       Another       Another       Another

The amount of rows will change daily, but the column number will always stay the same. What is the best way to do this?

like image 927
shinjuo Avatar asked Jul 25 '10 04:07

shinjuo


People also ask

Which method is commonly used to format the output?

String provides format() method can be used to print formatted output in java.

What is Perl format?

Formats are the writing templates used in Perl to output the reports. Perl has a mechanism which helps in generating simple reports and charts. Instead of executing, Formats are declared, so they may occur at any point in the program.

What is the difference between printf and print in Perl?

print just outputs. printf takes a formatting string like "%3f" and uses it to format the output. sprintf is the same as printf except it doesn't actually output anything. It returns a formatted string.


2 Answers

printf

    printf "%-11s %-11s %-11s %-11s %-11s %-11s %-11s %-11s\n",
            $column1, $column2, ..., $column8;

Change "11" in the template to whatever value you need.

like image 111
mob Avatar answered Sep 19 '22 01:09

mob


You could use Perl's format. This is probably the "complicated" method that you don't understand, most likely because it gives you many options (left|center|right justification/padding, leading 0's, etc).

Perldoc Example:

Example:
   format STDOUT =
   @<<<<<<   @||||||   @>>>>>>
   "left",   "middle", "right"
   .
Output:
   left      middle    right

Here's another tutorial.


Working Example: (Codepad)

#!/usr/bin/perl -w    

use strict; 

   sub main{    
      my @arr = (['something1','something2','something3','something4','something5','something6','something7','something8']
                ,['else1'     ,'else2'     ,'else3'     ,'else4'     ,'else5'     ,'else6'     ,'else7'     ,'else8'     ]
                ,['another1'  ,'another2'  ,'another3'  ,'another4'  ,'another5'  ,'another6'  ,'another7'  ,'another8'  ]
                );
      
      for my $row (@arr) {
         format STDOUT =
@<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  @<<<<<<<<<<<<  
         @$row
.
         write;
      }

   }    
       
   main();   
like image 44
vol7ron Avatar answered Sep 22 '22 01:09

vol7ron