[英]How can I create columnar output in 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? 我怎样才能更改脚本以达到目标?
You can use Text::Wrap : 你可以使用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;
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. 虽然我不确定你的问题究竟是你希望输出的格式,但我可以告诉你,Perl语言中输出相当的关键是使用格式。
A primer on how to use them to achieve pretty much any output formatting you would like is Perl format primer . 关于如何使用它们来实现您想要的几乎任何输出格式的入门是Perl格式入门 。
#!/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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.