Perl, Trim White Space from a String

When we grep a bunch of string, there are white spaces where we wish to trim, especially the white space at the beginning and the end of a string. There is no trim function in Perl like trim in PHP. The Perl function below should help you to trim the string.


#!/usr/bin/perl


sub trim($);
sub ltrim($);
sub rtrim($);

sub trim($)
{
	my $trim_string = shift;
	$trim_string =~ s/^\s+//;
	$trim_string =~ s/\s+$//;
	return $trim_string;
}

sub ltrim($)
{
	my $trim_string = shift;
	$trim_string =~ s/^\s+//;
	return $trim_string;
}

sub rtrim($)
{
	my $trim_string = shift;
	$trim_string =~ s/\s+$//;
	return $trim_string;
}

my $long_string = "  \t  foo foo        bar \t \t bar          ";
print trim($long_string);