Perl: the Markov chain saw | |
PerlMonks |
How do I strip blank space from the beginning/end of a string?by faq_monk (Initiate) |
on Oct 08, 1999 at 00:20 UTC ( [id://602]=perlfaq nodetype: print w/replies, xml ) | Need Help?? |
Current Perl documentation can be found at perldoc.perl.org. Here is our local, out-dated (pre-5.6) version: Although the simplest approach would seem to be:
$string =~ s/^\s*(.*?)\s*$/$1/; This is unneccesarily slow, destructive, and fails with embedded newlines. It is much better faster to do this in two steps:
$string =~ s/^\s+//; $string =~ s/\s+$//; Or more nicely written as:
for ($string) { s/^\s+//; s/\s+$//; }
This idiom takes advantage of the
# trim whitespace in the scalar, the array, # and all the values in the hash foreach ($scalar, @array, @hash{keys %hash}) { s/^\s+//; s/\s+$//; }
|
|