$text = '';$file = "text.txt";$word=''; open(IOfile,"$file") or die "The file $file could not be found, stopped "; $next = ;$total = length $next; $debug = shift @ARGV if @ARGV; open(DEBUG,">debug.txt") if $debug;select DEBUG if $debug; LINE: while($line = $next) { next LINE if $line =~ /^$/; $next = ; $sCount = $total - length($line); print "LINE: while loop\n" if $debug; print "Line eq '$line'\t\tNext eq '$next'\n" if $debug; print "Total eq $total\t\tsCount eq $sCount\n" if $debug; sCount: while($sCount) { print "sCount: while(sCount) loop\n" if $debug; $line =~ s/^[ \t]+//; $next =~ s/^[ \t]+//; $line =~ s/[ \t]+$//; $next =~ s/[ \t]+$//; $word = $1 if $next =~ /^([^ ]+)/; $wLength = length($word); $words = 0; $words++ while $line =~ /[^ ]+ */g; print "\tLine eq '$line'\t\tNext eq '$next'\n" if $debug; print "\tWord eq '$word'\t\twLength eq $wLength\n" if $debug; print "\tWords eq $words\n" if $debug; while(length($line) > $total) { #Too much text on this line print "while(length(\$line) > \$total) loop\n" if $debug; print "\tline to long\n" if $debug; if ($line =~ /[\t ]/) { #More than one word on line $next =~ s/$next/$1 . $next/e if $line =~ s/ +(\S+) *$//; print "\t\$1 eq '$1'\n" if $debug; print "\tmultiple words\tNew lines now equal:\n" if $debug; print "\tLine eq '$line'\t\tNext eq '$next'\n" if $debug; } else { #Only one word, so hyphenate $next =~ s/\n//g; $line =~ s/\n//g; $next = substr($line,$total) . " $next\n"; $line = substr($line,0,$total-1) . "-\n"; substr($line,$total) = ''; print "one word\n\tNew lines now equal:\n" if $debug; print "\tLine eq '$line'\t\tNext eq '$next'\n" if $debug; } $sCount = $total - length($line); print "sCount eq $sCount\n" if $debug; redo sCount; } if ($wLength < $sCount) { #See if first word on next line will fit in line $line =~ s/\n//g; $line =~ s/$line/$line . $word . "\n"/e; substr($next,0,$wLength) = ''; print "add word to first line\t\tlines now eq\n" if $debug; print "Line eq '$line'\t\tNext eq '$next'\n" if $debug; } elsif ( (($sCount > $words) and ($wLength-($sCount-2) > 3)) ) { #For hyphenation(must fit specific qualifications) $line =~ s/\n//g; $wPart = substr($next,0,$sCount-2); $next =~ s/$wPart//e; $line =~ s/$line/$line . $wPart . "-\n"/e; print "hyphenating\t\tLines now eq\n" if $debug; print "\$wPart eq '$wPart'\n" if $debug; print "Line eq '$line'\t\tNext eq '$next'\n" if $debug; } else { print "Add Spaces\n" if $debug; $line =~ s/([^ ]+ )/$1 /g if $sCount == $words; $line =~ s/([^ ]+ )/$1 / unless $sCount == $words; print "New lines now equal\n" if $debug; print "Line eq '$line'" if $debug; } next LINE; } } continue { $line .= "\n" if $line !~ /\n$/; $text .= $line;} open(IOfile,">$file"); select IOfile; print IOfile "$text";