in reply to Smart Substrings

I rather like punkkid's answer but, in the spirit of TIMTOWTDI, here's another way.

my $index = rindex($string, ' ', 15); # Chop it at 15 even if we didn't find a space... $index = 15 if($index < 0); $string = substr($string, 0, $index);

Note, however, that this will be foiled on words separated with more than one space... Or tabs.

You could, of course, do away with the synthetic variable ($index) if you don't care about chopping non-space containing strings... But you probably do. That would make it a one-liner. =)

bbfu
Seasons don't fear The Reaper.
Nor do the wind, the sun, and the rain.
We can be like they are.

Replies are listed 'Best First'.
Re: (bbfu) Re: Smart Substrings
by MeowChow (Vicar) on Apr 03, 2001 at 05:26 UTC
    A bit opaque, but you can do this for a one-liner:
    my $short = substr($string, 0, rindex($string, ' ', $len) + 1 || $len) +;
    This leaves you a trailing space, however.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print