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

Yes, but why? It works fine, but substr is quicker and easier to understand.

my $short = ( m/^(.{1,20})/ ) ? $1 : '';

...or...

my( $short ) = m/^(.{0,20})/;

Dave

Replies are listed 'Best First'.
Re^4: how to shorten given string?
by bart (Canon) on Oct 14, 2004 at 01:57 UTC
    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.

      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.