I had to take a sentence, and truncate it at a certain length, but I didn't want to cut it off in the middle of a sentence, so I used rindex to first start at the length specified, and go back till I found a space, and then cut it off there.
After I got that done, I modified it a little, to then allow for another argument to be passed that allowed for trailing characters, such as ...
And after I had gotten that done, I decided to either return the truncated string, OR an array, the first element would be the short string, and the second the rest of the array, depending on the output wanted using wantarray.
############################### cutoff ############################### # USAGE: # # $cutoff = cutoff($string, $length, $end); # # ($cutoff, $restofstring) = cutoff($string, $length, $end); # # $string is the string you want to be cut off at a given length # # $length is the position you want to start at # # $end is what to put at the end, like a ... # # By using rindex, it will start at that spot, if it is in the # # middle of a word, it will move back till it finds a space and cuts # # it off at that point. # # Since it uses wantarray, if you want an array back, it will return # # the portion you want, and the rest of the string. Otherwise, it # # will return just the cutoff portion. # ###################################################################### sub cutoff { my $string = shift; # get the string to examine my $size = shift; # get the size to "cut off" at my $end = shift; # characters to pad the end (...) my $length = length($string); # get the length if ($length <= $size) { # If the length is less than or return($string); # equal to the size we want to cut # off at, don't cut off } # end if else { # This takes the string, and uses rindex (same as index, but # reverse). It starts at $size, and goes back till it finds a # space and returns that position my $pos = rindex($string, " ", $size); # With the position to turnicate from, this uses substr to # acomplish this. my $cutstring = substr($string, 0, $pos); my $restofstring = substr($string, $pos, length($string)); $restofstring =~ s/^\s//; # Remove just the first space $cutstring .= $end if ($end); # If we want an array, return $cutstring, and $restofstring # otherwise return just $cutstring return wantarray ? ($cutstring, $restofstring) : $cutstring; } # end else } # end cutoff ######################################################################
In reply to Truncate string by lshatzer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |