开发者

How can I create columnar output in Perl?

开发者 https://www.devze.com 2022-12-23 07:29 出处:网络
!/usr/bin/env perl use warnings; use strict; my $text = \'hello \' x 30; printf "%-20s : %s\\n", \'very important text\', $text;

!/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开发者_StackOverflow 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?


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


Try this ,

use strict;
use warnings;

 my $text = 'hello ' x 30;

 $text=~s/((\b.+?\b){8})/$1\n                       /gs;
 printf "%-20s : %s\n", 'very important text', $text;


#!/usr/bin/env perl
use warnings; 
use strict;
use 5.010;
use Text::Wrap;
use Term::Size;

my $text = 'hello ' x 30;
my $init = ' ' x 22;
my( $columns, $rows ) = Term::Size::chars *STDOUT{IO};
$Text::Wrap::columns = $columns;

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


While I am not sure from your question precisely what format you would like your output in, I can tell you that the key to pretty output in the Perl language is to use formats.

A primer on how to use them to achieve pretty much any output formatting you would like is Perl format primer.

0

精彩评论

暂无评论...
验证码 换一张
取 消