Is there a way to do this in one line?
$x =~ s/^\\s+//;
$x =~ s/\\s+$//;
In other words, remove all leading and trailing whitespace from a stri
Arguing from the heretical, why do it at all? All of the above solutions are "correct" in that they trim whitespace from both sides of the string in one pass, but none are terribly readable (expect maybe this one). Unless the audience for your code is comprised of expert-level Perl coders each of the above candidates should have a comment describing what they do (probably a good idea anyway). By contrast, these two lines accomplish the same thing without using lookaheads, wildcards, midichlorines or anything that isn't immediately obvious to a programmer of moderate experience:
$string =~ s/^\s+//;
$string =~ s/\s+$//;
There is (arguably) a performance hit, but as long as you aren't concerned with a few microseconds at execution the added readability will be worth it. IMHO.