How to trim whitespaces in a string, leading and trailing

This tutorial shows multiple ways to remove whitespace characters from a given string in Perl.

  • using the String::Util module trim function to remove leading and trailing spaces. Example trim(” abc ”) returns abc.
  • using String pattern matching operator =~
  • use the Text::Trim module trim function

How to trim leading and trailing whitespace characters in Perl string

The String::Util module contains trim functions and removes the lead and trail whitespace characters. Install the module using the below command in the windows terminal.

cpan String::Util



Here is an example to remove the start and end whitespace characters from the string

use String::Util 'trim';
my $str = "  test  ";
$result = trim($str);
print "$result\n";



It removes any whitespace symbols if the string contains new line (\n) or tab(\t) characters,

use String::Util 'trim';
my $str = "" \tHello Welcome \n"
$result = trim($str);
print "$result\n";


Hello Welcome

String removes All whitespace in Perl using pattern matching operator

String provides pattern matching operator =~ in Perl to match a string with a regular expression

The pattern used here to trim white space is s/^\s+|\s+$//g; Here is an example

my $str = " Hello Welcome ";
$str =~  s/^\s+|\s+$//g;
print "$str\n";


Hello Welcome

String remove all whitespaces with regular expression

Another way, use the Text::Trim module provides the trim function, returns a string by removing all white spaces at beginning and end of a string Here is an example program

use Text::Trim;
print trim("  hello  ");





Learn multiple ways to remove all whitespace in a string.