input : string (sentence) output: truncated string at period, question mark or exclamation point
# input : string (sentence) # output: truncated string at period, question mark or exclamation poi +nt sub strim { my ($s, $i) = @_; $s =~ s/^\s+$//g; return $s unless defined $i; if (length $s <= $i) { return $s; } else { while (right(left($s, $i), 2) ne '. ' && right(left($s, $i), 2) ne '? ' && right(left($s, $i), 2) ne '! ') { $i--; return left($s, $_[1]) if ($i < 1); } return left($s, $i); } } # input : string, integer # output: truncated string sub left { my ($s, $i) = @_; return unless defined $s; return $s unless defined $i; return substr($s, 0, $i); } # input : string, integer # output: truncated string sub right { my ($s, $i) = @_; return unless defined $s; return $s unless defined $i; return substr($s, length($s) - $i, $i); }

Replies are listed 'Best First'.
Re: Truncate a string (news lead?)
by premchai21 (Curate) on Sep 12, 2001 at 06:37 UTC
    sub foo{($_[0]=~/^(.+[!?.]\s)/s)?$1:$_[0]}
    Update: Fixed (twice) according to merlyn's correction(s).
        except my example truncates @ any number of starting characters, not just the first sentence.
      ($_[0]=~/^(.+[!?.]\s)/s)&&$1||$_[0]
      Do not use XX && YY || ZZ when you mean XX ? YY : ZZ, or the day your YY returns false, you will be kicking yourself.

      I don't know where this idiom started, but please do not propagate it.

      -- Randal L. Schwartz, Perl hacker

        /me kicks himself.

        You're right, though for a different reason. It seems to me that, in this particular case, YY ($1) cannot be false, as it contains at least one character, then one of !?., then a whitespace character. Which cannot be false. Or, if the match fails, it contains nothing and therefore is false as it is supposed to be. Usually.

        However, it might contain the $1 from a previous match, which makes you right. Again.