in reply to Re^3: how to shorten given string?
in thread how to shorten given string?

Try
s/^(.{1,20}).*/$1/;
and it's short enough.

Why use a regexp? What if he wants a trailing ellipsis (= 3 dots) in case the string is shortened?

s/^(.{1,20})(.+)?/$1 . (defined $2 ? "..." : "")/e;
The neat thing about using regexes is that it's easy to modify to make it sing and dance, once the requirements change ever so slightly.

Replies are listed 'Best First'.
Re^5: how to shorten given string?
by davido (Cardinal) on Oct 14, 2004 at 03:08 UTC

    I'll accept that reasoning. :)

    Here's a version of your 'add elipses' regexp that shifts the code evaluation to the left side of the s/// operator by using (?{...}). Not as clear as your solution, but another way to do it. I'm always looking for entertaining ways to use (?{...}). ...your approach is more appropriate for actual use though. Keep mine in the cage.

    $string =~ s/^(.{1,20})(?{(length($_)>pos)?'...':''}).*$/$1$^R/;

    Just for fun... ;)


    Dave

      Wicked.