#!/usr/bin/env perl use strict; use warnings; use feature 'say'; use utf8; use open qw(:std :utf8); my $WIDTH_DEFAULT = 80; my $WIDTH = $ARGV[0] || $WIDTH_DEFAULT; sub main { my $buf = ''; while (my $line = ) { if ($line =~ /^\s+$/) { say $buf; say '' if ($buf); $buf = ''; next; } if ($buf) { $line = $buf . $line; } my ($head, $tail) = handle_str($line); say $head; $buf = handle_buf($tail); } say $buf if $buf; } sub handle_buf { my $buf = shift; my $len = length($buf); if ($len == $WIDTH) { say $buf; return ''; } if ($len < $WIDTH) { return $buf; } ## $len > $WIDTH my ($head, $tail) = handle_str($buf); say $head; handle_buf($tail); } sub handle_str { my $str = shift; if ($str =~ m/^(.{0,$WIDTH})\s(.*)$/) { return ($1, $2); } ## no spaces here: 0..$WIDTH if ($str =~ m/^(\S*)\s(.*)$/) { return ($1, $2); } ## no whitespace at all if ($str =~ m/^(\S+)$/) { return ($1, ''); } die "ooops!"; } main();