wrapLine

Perl

Public Domain

Fold lines at 80 characters (or any other point)

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# wrapLine takes a string of text (which should not contain any
# newlines) and an optional line length (default 80).  It returns a
# list of lines (without any terminating newlines) each no longer
# than the specified width.  Lines are broken at whitespace or in
# the middle of very long words.

sub wrapLine($;$) {
 my $str = shift;
 my $len = shift || 80;
 $str =~ s/\s+$//;
 my @lines = ();
 while (length $str > $len) {
  if (reverse(substr $str, 0, $len) =~ /\s+/) {
   push @lines, substr $str, 0, $len - $+[0], ''
  } else { push @lines, substr $str, 0, $len, '' }
  $str =~ s/^\s+//;
 }
 return (@lines, $str);
}