If you are willing to use a CPAN module then String::Util, or the somewhat more economical Text::Trim would be possible choices.
Trimming strings is one of those bike sheds that everyone likes to build! See the short perlmaven tutorial by @szabgab for a small sample of TIMTOWDI fun.