smith
smith

Reputation: 3262

formatting text with perl

I have the a text on this template :

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 .

and want to convert every paragraph to one line seprated by "\n" i.e the output will be:

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 .

how can i format such thing with perl could someone provide an example ?

I tried to use Text::Wrap like below but get unwanted results

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

Upvotes: 1

Views: 406

Answers (3)

TLP
TLP

Reputation: 67900

For a one-liner, you might try something like this:

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

-00 will set the input record separator $/ to "" and activate paragraph mode. -l will set output record separator $\ to "\n\n" (in this case).

In script version:

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

Upvotes: 2

Dave Cross
Dave Cross

Reputation: 69224

You can do it with Text::Wrap but a) you need to read the file a paragraph at a time and b) you need to set an artificially high right margin.

#!/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 .

Upvotes: 2

Alien Life Form
Alien Life Form

Reputation: 1944

#!/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";}

Upvotes: 0

Related Questions