使用perl格式化文本

时间:2012-01-31 14:13:09

标签: perl

我在这个模板上有一个文字:

In 1935 he was asked to document the principal dancers and productions and 
George newly .

he continued to shoot fashion 
Bergdorf Goodman and Saks Fifth 
started a series of photographs .

并希望将每个段落转换为由“\​​ n”分隔的一行,即输出将为:

In 1935 he was asked to document the principal dancers and productions George newly .

he continued to shoot fashion Bergdorf Goodman and Saks Fifth started a series of photographs .

我如何使用perl格式化这样的东西可以有人提供一个例子吗?

我尝试使用如下所示的Text :: Wrap,但得到了不需要的结果

$Text::Wrap::separator=' ';
my $text=fill("","",$text);

3 个答案:

答案 0 :(得分:2)

你可以用Text :: Wrap来做,但a)你需要一次读一个段落的文件,b)你需要设置一个人为的高右边距。

#!/usr/bin/perl

use strict;
use warnings;

use Text::Wrap;

$Text::Wrap::columns = 10_000;
local $/ = ''; # Always localise changes to $/

while (<DATA>) {
  print fill('', '', $_), "\n\n";
}

__DATA__
In 1935 he was asked to document the principal dancers and productions and 
George newly .

he continued to shoot fashion 
Bergdorf Goodman and Saks Fifth 
started a series of photographs .

答案 1 :(得分:2)

对于单行,您可以尝试这样的事情:

perl -00 -l -pwe 's/\n//g' foo/george.txt 

-00会将输入记录分隔符$/设置为""并激活段落模式。 -l会将输出记录分隔符$\设置为"\n\n"(在本例中)。

在脚本版本中:

$/ = ""; 
$\ = "\n\n";
while (<>) {
    chomp;
    s/\n//g;
    print;
}

答案 2 :(得分:0)

#!/usr/bin/perl
use strict;
use warnings;

$/=""; #lines are paragraphs - perlfaq5
#files are command line args, or STDIN
while(<>){s/\n//g; print $_,"\n\n";}