in reply to how to shorten given string?

$str = "Ipod batteries for Apple Ipod PDAs. Replacement batteries from + Laptops for Less.com.url"; $short = substr($str, 0, 20);
Also, see the substr doc from Perldoc.com.

Replies are listed 'Best First'.
Re^2: how to shorten given string?
by mellin (Scribe) on Oct 13, 2004 at 18:50 UTC
    What if i want to do it with regexp, is there a way to do it like that?

      Your posted code will work if you remove the space after the comma in your regex.

      /^(.{1, 20}).*/; # doesn't work /^(.{1,20}).*/; # does work /^(.{1,20})/; # even easier
      May the Force be with you

      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

        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.
      What if i want to do it with regexp, is there a way to do it like that?
      What if I was given a perfectly good working solution, and then I said "No, I want to do it some other way"? Would people think I was asking a homework question? Maybe. Maybe not.

      In any event, if this wasn't a homework question, you should have given more background about why substr didn't suffice, so that we know why you rejected that solution.

      And it looks like I'm not the only one who wonders this.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

      Others here are better (and faster) with regexps than I. They have provided answers below. My question to you would be:
      What is the reason for wanting to use a regex to perform a substr on a string when there's a substr function already?

        Just to understand better of the meanining of code i'm writing , nothing more :) Thank you all very much. Next thing to do would be including three dots like "..." after the shortened string, but if only the string was longer than given length. Like printing "Ipod batteries for Apple iPod...", because original string exceeded 30 chars. If the string fits under given amount of characters, it is displayed as is. I'll try to implement that now, but if you guys are faster, feel free, please :P