shinjuo
shinjuo

Reputation: 21012

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?

Upvotes: 9

Views: 41387

Answers (4)

lochii
lochii

Reputation: 91

I would look at formatting, but I would do it using Perl 6's (now Raku) Form.pm, which you can obtain as Perl6::Form for Perl 5.

The reason for this is that the format builtin has a number of drawbacks, such as having the format statically defined at compile time (i.e., building it dynamically can be painful and usually requires string eval), along with a whole list of other shortcomings, such as lack of useful field types (and you can't extend these in Perl 5).

Upvotes: 4

vol7ron
vol7ron

Reputation: 42099

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();   

Upvotes: 12

bessarabov
bessarabov

Reputation: 11851

Here is a live example of Perl6::Form:

#!/usr/bin/perl

use Perl6::Form;

my @arr = (
    [1..8],
    [9..16],
    [17..24],
);

foreach my $line (@arr) {
    print form
        "{<<<<<} "x8,
        @{$line};
}

It will output:

1       2       3       4       5       6       7       8
9       10      11      12      13      14      15      16
17      18      19      20      21      22      23      24

Upvotes: 4

mob
mob

Reputation: 118595

printf

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

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

Upvotes: 18

Related Questions