Trim a string in Perl

There are several ways to trim a string in perl. Below is one of those. I've used a simple regular expression (REGEX) that just removes the whitespaces from the begin and end of a string.


## Trim function.
sub trim{
   my $string = shift;
   $string =~ s/^\s+|\s+$//g;
   return $string;
}
print "[".trim(" just trimming a string ")."]\n";

Alternately if you like a nicer way (i.e. use a function) then you could use this.
use String::Util qw(trim)

Comments