Wrap text blocks in either a file or from STDIN. Nothing fancy or smart here, just some simple functional code.

Update: now deals with indentation correctly

#!/usr/bin/perl use strict; use Text::Wrap; use IO::File; die "Usage: wrap.pl FILE [WIDTH]\n" if @ARGV == 0 or $ARGV[0] =~ /^--?h/; $Text::Wrap::columns = ( @ARGV == 2 and $ARGV[1] =~ /^\d+$/ ) ? pop @ARGV : 80; if( $ARGV[0] eq '-' ) { print process_data( \*STDIN ); exit(0); } my $fn = shift @ARGV; my $fh = IO::File->new($fn, 'r+') or die("wrap.pl: $! - [$fn]\n"); my @wrapped = process_data($fh); $fh->seek(0, 0); $fh->truncate( 0 ); $fh->print( @wrapped ); $fh->close() or die("wrap.pl: $! - [$fn]\n"); exit(0); sub process_data { my $fh = shift; my @data = map { chomp; $_ } <$fh>; my $initial_indent = $data[0] =~ /^(\s+)/ ? $1 : ''; my $subsequent_indent = $data[1] =~ /^(\s+)/ ? $1 : ''; s/^\s*// for @data; return fill( $initial_indent, $subsequent_indent, @data ); } __END__ =pod =head1 NAME wrap.pl - basic wrapper around C<Text::Wrap>'s C<fill()> function =head1 USAGE wrap.pl filename $COLNUM The first argument can either be a filename or C<-> to indicate that input will be from C<STDIN>. The second argument (optional) will be the column width which the text will be wrapped at. =head1 TODO =over 6 =item * Use C<Pod::Usage> and the like =back =cut

Replies are listed 'Best First'.
Re: Small wrapper for Text::Wrap's fill()
by Aristotle (Chancellor) on Jul 31, 2003 at 20:20 UTC
    If you're on a GNU system, you should probably check man fmt. It may be available on other Unices as well.

    Makeshifts last the longest.

Re: Small wrapper for Text::Wrap's fill()
by sauoq (Abbot) on Aug 01, 2003 at 02:55 UTC

    Funny. I've been using this little script, which I named simply "wrap", for ... uh ... well, years now that I think about it. It's a wrapper around Text::Wrap's wrap() function. If I recall, I wrote it because I wanted to be able to use the "initial_tab" and "subsequent_tabs" feature of Text::Wrap. It only outputs to stdout. I generally call it from vi and haven't needed to write the output directly to a file, but if I ever do there's always redirection.

    #!/usr/bin/perl -w use strict; # Description: Text wrapper kind of like fmt. use Getopt::Std; use Text::Wrap; my $USAGE =<<EOU; $0: [-c columns] [-i initial_tab] [-s subsequent_tabs] [-h] file ... -c Set column width for wrapping. -i Set initial 'tab' string for first paragraph line. -s Set a 'tab' string for subsequent paragraph lines. EOU local $/ = ''; my %O; getopts("c:i:s:h", \%O); if ($O{'h'}) { print $USAGE; exit; } $Text::Wrap::columns = $O{'c'} || 80; my $inittab = exists $O{'i'} ? eval("qq($O{'i'})") : ''; my $subtabs = exists $O{'s'} ? eval("qq($O{'s'})") : ''; while (<>) { s/\n/ /g; $_ .= "\n\n"; print Text::Wrap::wrap($inittab, $subtabs, $_); }

    -sauoq
    "My two cents aren't worth a dime.";