in reply to How do I truncate a string while preserving words?

Although others have solved the problem with the presented code, I'd have separated out the functional behaviour for maintenability and potential change impacting each subrule rather than implement multiple functions in a single regexp. e.g.:
sub truncate_string($$) { my ( $string, $max ) = @_; # always do nothing if already short enough ( length( $string ) <= $max ) and return $string; # issue warning if forced to chop a word anyway if ( $string =~ /\s/ ) { warn "cannot truncate string on word boundary"; return substr( $string, 0, $max ); } # truncate pre-existing trailing whitespace $string =~ /^(.*)\s+$/ and return $1; # otherwise truncate on word boundary $string =~ s/\S+$// and return $string; die; # unreachable }
__________________________________________________________________________________

^M Free your mind!