in reply to Smart Substrings

I think the method is a bit cumbersome. And you could get ugly multiple "..."s - at least, the way you have written the algorithm. Rather than continually shortening the string, why not just:

1. Check if it is too long
2. If not, print it
3. If so, get the last word and as many words from the start as you can, then put a "..." in. If the last word is more than 12 chars, just get as many words from the start as you can; if the first word is more than 12 chars, truncate it.

Short and simple. Although I think sometimes people obsess about speed... if it's building a webpage, this is not an algorithm that is gonna be run a million times. But simple code is easy to debug.

if (length ($string) > 15) { my $last; if ($string =~ /\s(\S{1,12})$/) { $last = $1; # a suitable end word } $starting_length = 12 - length($last); if ($string =~ /(.{0,$starting_length})\s/) { # greedy pattern match +, matches multiple words $string = "$1...$last"; } else { $string = substr($string,0,12) . "..."; } }

You could prolly do that last if.. else just with s/// and checking if the match was successful:

( $string =~ s/(.{0,$starting_length})\s/"$1...$last"/e ) or $string = + substr($string,0,12) . "...";

Actually, you really want to check the first word length first. You probably want words from the start rather than the end (more recognisable), but this grabs as much as it can from the end, then cuts the start to suit. Well, play with it. dave hj~