PERL:使用Text :: Wrap并指定行尾

时间:2014-03-09 10:36:06

标签: perl word-wrap

是的,我正在重写cowsay:)

#!/usr/bin/perl

use Text::Wrap;
$Text::Wrap::columns = 40;

my $FORTUNE = "The very long sentence that will be outputted by another command and it can be very long so it is word-wrapped The very long sentence that will be outputted by another command and it can be very long so it is word-wrapped";

my $TOP = " _______________________________________
/                                       \\
";
my $BOTTOM = "\\_______________________________________/
";

print $TOP;
print wrap('| ', '| ', $FORTUNE) . "\n";
print $BOTTOM;

制作此

 _______________________________________
/                                       \
| The very long sentence that will be
| outputted by another command and it
| can be very long so it is
| word-wrapped The very long sentence
| that will be outputted by another
| command and it can be very long so it
| is word-wrapped
\_______________________________________/

我怎么能得到这个?

 _______________________________________
/                                       \
| The very long sentence that will be   |
| outputted by another command and it   |
| can be very long so it is             |
| word-wrapped The very long sentence   |
| that will be outputted by another     |
| command and it can be very long so it |
| is word-wrapped                       |
\_______________________________________/

2 个答案:

答案 0 :(得分:2)

我在文档中找不到方法,但是如果你保存字符串,你可以应用一个小的hack。可以使用包变量分配一个新行结尾:

$Text::Wrap::separator = "|$/";

您还需要阻止模块扩展标签并弄乱字符数:

$Text::Wrap::unexpand = 0;

这只是一个管道|,后跟输入记录分隔符$/(最常见的换行符)。这将在行尾添加一个管道,但没有填充空间,必须手动添加:

my $text = wrap('| ', '| ', $FORTUNE) . "\n";
$text =~ s/(^.+)\K\|/' ' x ($Text::Wrap::columns - length($1)) . '|'/gem;
print $text;

这将匹配每行的开头,以|结尾,通过将空格乘以列减去匹配字符串的长度来添加填充空间。我们使用/m修饰符使^匹配字符串中的换行符。 .+本身与新行不匹配,这意味着每个匹配将是整行。 /e修饰符会将替换部分“评估”为代码,而不是字符串。

请注意,它有点快速破解,因此可能存在错误。

答案 1 :(得分:2)

如果您愿意下载更强大的模块,可以使用Text::Format。它有更多的自定义选项,但最相关的选项是rightFill,它用空格填充每行中的其余列。

不幸的是,您无法使用非空格字符自定义左侧和右侧。您可以通过执行正则表达式替换来使用解决方法,就像Text::NWrap在其源代码中所做的那样。

#!/usr/bin/env perl

use utf8;
use Text::Format;

chop(my $FORTUNE = "The very long sentence that will be outputted by another command and it can be very long so it is word-wrapped " x 2);

my $TOP =  "/" . '‾'x39 . "\\\n";
my $BOTTOM = "\\_______________________________________/\n";

my $formatter = Text::Format->new({ columns => 37, firstIndent => 0, rightFill => 1 });
my $text = $formatter->format($FORTUNE);
$text =~ s/^/| /mg;
$text =~ s/\n/ |\n/mg;

print $TOP;
print $text;
print $BOTTOM;