Multiple Ways to Remove Whitespace Characters from a String in Perl

This tutorial demonstrates various methods 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

Using the String::Util Module’s trim Function

One approach is to utilize the trim function from the String::Util module to eliminate leading and trailing spaces. For example, trim(" abc ") returns “abc”.

To install the String::Util module, execute the following command in the Windows terminal:

cpan String::Util



Here’s an example to remove leading and trailing whitespace characters from a string

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



This function also removes any whitespace symbols, including newline (\n) or tab (\t) characters.

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


Hello Welcome

Using the Pattern Matching Operator =~ for String Manipulation

Perl provides the pattern matching operator =~ to match a string with a regular expression. We can use it to trim whitespace characters using the pattern s/^\s+|\s+$//g.

Here is an example

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


Hello Welcome

Removing All Whitespaces with Regular Expression

Alternatively, you can utilize the Text::Trim module, which provides the trim function. This function returns a string by removing all leading and trailing whitespace.

Here is an example program

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




This tutorial highlights multiple methods to eliminate whitespace characters from a string in Perl, providing flexibility and versatility in string manipulation.