in reply to Re^2: In search of a better way to trim string length
in thread In search of a better way to trim string
Maybe a little explanation will help?
sub trimTo { my( $str, $n ) = @_; ## Give back what they gave us if the nothing to do return $str if length $str < $n; my $lastSpace = 1 + rindex( $str, ' ', $n-3 ); ## Subtracting 3 allows for adding the '...' ## rindex finds the last space preceding the position ## or -1 if it fails. ## Adding 1 means that we can test whether it found the space +with ## if( 1+rindex...) { ... ## or supply a default value ## 1 + rindex( ... ) || $default ## It also means that we get a length that we can supply ## directly to substr without having to increment it. substr( $str, 0, $lastSpace || $n-3 ) . '...'; ## The substr( ... ) returns from the start of string ## to the first space before the postition-3 (including that space +) ## or the first $n characters of the string. ## Combining the two avoids a temporary var. ## Tack on the '...' }
With respect to the 'bug'. I actually consider the difference a bonus in as much as "stuff ..." indicates that there are more words that were truncated.
Whereas "stuff..." indicates that the word itself was truncated.
If you prefer the other behaviour, then this will do it.
sub trimTo { my( $str, $n ) = @_; return $str if length $str < $n; my $lastSpace = 1 + rindex( $str, ' ', $n-3 ); ## Truncate length allowing to always include the ' ' before '. +..' my $truncLen = ( $lastSpace || $n-3 ) - 1 ; return substr( $str, 0, $truncLen ) . ' ...'; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: In search of a better way to trim string length
by Your Mother (Archbishop) on Jul 19, 2004 at 19:06 UTC | |
by dragonchild (Archbishop) on Jul 19, 2004 at 19:37 UTC | |
by BrowserUk (Patriarch) on Jul 19, 2004 at 20:12 UTC | |
Re^4: In search of a better way to trim string length
by kiat (Vicar) on Jul 19, 2004 at 10:15 UTC |
In Section
Seekers of Perl Wisdom