Trimming Blanks from the Ends of a String

Using Perl to trim a string is very easy. You can use below pattern substitutions to get rid of a leading or trailing whitespace.

$string =~ s/^\s+//; # trim leading
$string =~ s/\s+$//; # trim trailing

You can combine them together to trim both of leading and trailing whitespace
$string =~ s/^\s+|\s+$//g;

Below is script to implement trim function:

#! /usr/local/bin/perl

#luohua.huang@gmail.com

#################################
# Trimmin Blanks from a string have leading or trailing whitespace
##################################
sub trim
{
my @out = @_;
for (@out) {
s/^\s+//; # trim leading
s/\s+$//; # trim trailing
}

return @out == 1

? $out[0] # only one to return
: @out; # or many

}

$string = ” abc “;
$string = trim($string);
print “$string \n”;

@many = (” many1 “,”many2 “, ” many3″);
@many = trim(@many);
for (@many) {
print “$_ \n”;
}

Output:

(luhuang) public_html- ./trim.pl
abc
many1
many2
many3