sid_com sid_com - 7 months ago 13
Perl Question

How can I create columnar output in Perl?

!/usr/bin/env perl



use warnings;
use strict;

my $text = 'hello ' x 30;

printf "%-20s : %s\n", 'very important text', $text;


The output of this script looks more ore less like this:

very important text : hello hello hello hello
hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello
...


But I would like an output like this:

very important text: hello hello hello hello
hello hello hello hello
hello hello hello hello
...


I forgot to mention: The text should have an open end in the sense that the right end of the textlines should align corresponding to the size of the terminal.

How could I change my script to reach my goal?

Answer

You can use Text::Wrap:

use strict;
use Text::Wrap;

my $text = "hello " x 30;
my $init = ' ' x 20;
$Text::Wrap::columns = 80;

print wrap ( '', $init,  'very important text : ' . $text );