To trim a string in Perl, you can use the trim()
function from the String::Util
module.
In this example,
trim()
function from the String::Util
module to remove leading and trailing whitespace characters from the string " Hello World "
.use String::Util qw(trim);
my $str1 = " Hello World ";
my $trimmed_str1 = trim($str1);
print "Trimmed string is: '$trimmed_str1'\n";
Trimmed string is: 'Hello World'
In this example,
trim()
function from the String::Util
module with the left
option to remove leading whitespace characters from the string " apple"
.use String::Util qw(trim);
my $str2 = " apple";
my $trimmed_str2 = trim($str2, 'left');
print "Trimmed string is: '$trimmed_str2'\n";
Trimmed string is: 'apple'
In this example,
trim()
function from the String::Util
module with the right
option to remove trailing whitespace characters from the string "banana "
.use String::Util qw(trim);
my $str3 = "banana ";
my $trimmed_str3 = trim($str3, 'right');
print "Trimmed string is: '$trimmed_str3'\n";
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Perl language with well detailed examples.