Trim whitespaces with Perl

By | September 2, 2009

If you want to remove white spaces with Perl, you can use the following Reggular Expressions

Trim all whitespaces: $value=~s/s*//g; # remove all the whitespace

Or you can use function to trim the whitespaces from beggining, ending or both:

# Perl trim function to remove whitespace from the start and end of the string
sub trim($){
my $string = shift;
$string =~ s/^s+//;
$string =~ s/s+$//;
return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($){
my $string = shift;
$string =~ s/^s+//;
return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($){
my $string = shift;
$string =~ s/s+$//;
return $string;
}
# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
my $string = shift;
$string =~ s/^s+//;
$string =~ s/s+$//;
return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
my $string = shift;
$string =~ s/^s+//;
return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
my $string = shift;
$string =~ s/s+$//;
return $string;
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.