{

How to trim whitespaces in a string, leading and trailing


 String leading trailing trim whitespace Perl with code example

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

Syntax:

trim(string)

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";

Output:

test

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";

Output:

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";

Output:

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  ");

}

Output:

hello

Conclusion

Learn multiple ways to remove all whitespace in a string.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.