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);
Might want to use String::Strip it’s faster. See this previous IronMan post http://www.illusori.co.uk/perl/2010/03/05/advanced_benchmark_analysis_1.html
Thanks, will look into that 😀