Perl format()问题 - 段落之间的空行被剥离,无法显示

时间:2011-04-09 09:18:32

标签: perl

我正在使用Perl的formatwrite函数输出一些文字。

要求如下:

  1. 使用Perl format打印文章(长度未知)。
  2. 每行最多80个字符。
  3. 如果没有足够的空间,最后一个字应该被包裹到下一行。
  4. 段落之间的空行需要保留。
  5. 我现在遇到的问题是段落之间的任何空白行都无法显示。我查了一下,这似乎是由于使用了“~~”。

    格式定义如下。

    format FULL_TEXT =
    Full Story:
    ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
    $storyBody
    .
    

    有没有办法在段落之间打印这条空行,同时还能满足其他要求?

    例如,以下是我的期望。但是,正如我之前所说,两段之间的空行被剥离,无法显示。

    昨晚,COLLINGWOOD在MCG展开了2010年的英超冠军旗帜 协议要求的场合,通过降低其颜色 最长的竞争对手,卡尔顿在一场史诗般的比赛中,如果没有 结果

    人群为88,181,这是这些俱乐部之间的主场和客场比赛的记录。在AFL中有一种古老的感觉。

2 个答案:

答案 0 :(得分:1)

use 5;
use strictures;
use Perl6::Form;

my $storyBody = 'COLLINGWOOD unfurled its 2010 premiership flag at the MCG last night and marked the occasion as protocol demanded, by lowering the colours of its longeststanding rival, Carlton in a contest that was epic in style, if not consequence.

The crowd was 88,181, a record for home-and-away contests between these clubs. An old feeling stirring in the AFL.';

my $form = form
'Full Story:',
'{[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[}',
map {s/\n/\r\r/; $_} $storyBody;

print $form;

输出:

Full Story:
COLLINGWOOD unfurled its 2010 premiership flag at the MCG last night and marked
the occasion as protocol demanded, by lowering the colours of its longeststanding
rival, Carlton in a contest that was epic in style, if not consequence.

The crowd was 88,181, a record for home-and-away contests between these clubs. An
old feeling stirring in the AFL.

Semantics of \r in form(?:at)?s

答案 1 :(得分:1)

诀窍是将文本拆分成段落并一次写下每个段落。

use strict;
use warnings;
# slurp text
my $text = do { local $/; <> };
# split into paragraphs
my @paragraphs = split /\n+/, $text;
# define format, including newline at the end
format STDOUT =
  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$_
  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
$_

.
# write text to format
write for @paragraphs;

这样称呼:

perl /tmp/fmt.pl < /tmp/article.txt

如果您想要或必须节省内存,因为您的文章太大,您可以结合前两个步骤:

use strict;
use warnings;
# slurp text into paragraphs
my @paragraphs = split /\n+/, do { local $/; <> };
# define format, including newline at the end
format STDOUT =
  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$_
  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
$_

.
write for @paragraphs; # write text to format