in reply to Smart Substrings

I'm not sure I like any of the solutions yet offered (can you tell?) so I whipped this up:
sub shorten { local $_ = shift; my $len = shift; my $pos; return $_ if $len >= length; $len -= 3; $pos = pos while /\w(?=\s)/g && $len >= pos; $pos ||= $len; substr($_, 0, $pos)."..."; } print shorten("misunderestimate", 15), "\n"; print shorten("all work and no play makes MeowChow a dull boy", 15), " +\n"; print shorten("imapirateiamiam", 15), "\n";
If you don't care about matching multiple spaces or about matching tabs, I would rewrite the second and third-to-last lines in the sub as follows (which would essentially make it bbfu's solution):
$pos = rindex $_, " ", $len; $pos = $len if $pos < 0;
This would make a good Golf contest by the way (hint, hint)...
   MeowChow                                   
               s aamecha.s a..a\u$&owag.print

Replies are listed 'Best First'.
Re: Smart Substrings
by cLive ;-) (Prior) on Apr 03, 2001 at 09:00 UTC
    LOL :)

    "Remember, just say NO to regex (when simpler functions will do)". - MeowChow

    sorry, couldn't resist it :)

    cLive ;-)

      I knew this would be coming...

      Yes, I did resort to a regex, but only because of two exceptional cases (extra spaces and tabs). Not knowing the poster's requirements in this regard, I wrote something that would handle these cases. The non-regex solution is still a much better fit to this problem, and the regex that I did use was kept fairly simple. It would even have been /\w\s\/, but I chose to simplify the indexing arithmetic instead.

      Hmm... all this backtracking, I'm beginning to sound like a regex myself :)

         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print