1.14. Trimming Blanks from the Ends of a StringProblemYou have read a string that may have leading or trailing whitespace, and you want to remove it. SolutionUse a pair of pattern substitutions to get rid of them: $string =~ s/^\s+//; $string =~ s/\s+$//; You can also write a function that returns the new value: $string = trim($string); @many = trim(@many); sub trim { my @out = @_; for (@out) { s/^\s+//; s/\s+$//; } return wantarray ? @out : $out[0]; } DiscussionThis problem has various solutions, but this is the most efficient for the common case.
If you want to remove the last character from the string, use the # print what's typed, but surrounded by >< symbols while(<STDIN>) { chomp; print ">$_<\n"; } See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|