各行が X 文字以内でもっとも多くの単語を含むように改行を挿入

#! /usr/bin/env perl

# convert a long line to fixed-length lines by adding line breaks

use strict;
use warnings;
use Getopt::Long;
my $line_length = 60;
GetOptions('line-length=i' => \$line_length);

my @to_print = ();
my $to_print_length = -1;
my @lines = <>;
chomp @lines;
foreach ( split / /, join '', @lines ) {
    if ( $to_print_length + 1 + length $_ <= $line_length ) {
        push @to_print, $_;
        $to_print_length += 1 + length $_;
    } else {
        print "@to_print\n";
        @to_print = $_;
        $to_print_length = length $_;
    }
}
print "@to_print\n";