in reply to Smart Substrings

I would do it like this:
$string =~ s/^(.{15}).+$/$1/;
To split between words and add .. I'd use:
$string =~ s/^(.{1,15})\s*.*$/$1.../;
This assumes you want a string 15 chars long + the "...", if there's not a space in the 15 chars it chops it there anyways.

- p u n k k i d
"Reality is merely an illusion, albeit a very persistent one." -Albert Einstein

Replies are listed 'Best First'.
Re: Re: Smart Substrings
by MeowChow (Vicar) on Apr 03, 2001 at 05:09 UTC
    Your first code snippet is a good example of bringing out the regex chain-gun when a simple substr would do:
    my $short = substr $string, 0, 15;
    This is equivalent, but faster and more readable. Don't use a regex unless you actually need it.

    Your second snippet doesn't split on words. You would need to change the \s* to a \s+ for it to do that, but then it would break on a starting word greater than 15 chars.

    I don't mean to offer harsh criticism, but one of my pet peeves is seeing regexes used when a simple index/substr would do.

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

      Why would you keep a peeve as a pet? Wouldn't a dog or a cat be more fun?

      (Sorry, couldn't resist ;^)