4th Floor, 4 Tabernacle Street London EC2A 4LU

Perl – Trim Text, Trim String

Left trim- ltrim or lstrip removes white spaces from the left side of a string:

[perl] $str =~ s/^\s+//;
[/perl]

Right trim – rtrim or rstrip removes white spaces from the right side of a string:

[perl] $str =~ s/\s+$//;

[/perl]

Trim Both

[perl] $str =~ s/^\s+|\s+$//g

[/perl] [perl]

my $x = trim (” HELLO “);

sub trim($)
{
# Remove LEft and right additional spaces
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}

[/perl]