If I declared a variable $myString
with the value \'3 \'
(notice the white space).
Is there any function to remove the white space for the return v
$myString =~ s/^\s*(.*?)\s*$/$1/;
This will trim whitespace from both sides.
from just the right:
$myString =~ s/\s*$//;
sub trim
{
my $str = $_[0];
$str=~s/^\s+|\s+$//g;
return $str;
}
print trim(" 4 ");
Here's a subroutine that will allow you to remove leading and trailing whitespace from a string while also removing excesss whitespaces from within the string and replacing it with a single spaces.
sub unspace { my @stringer = @_ ? @_ : $; $ = join( ' ', split(' ')) for @stringer; return wantarray ? @stringer : "@stringer"; }
$MySpacedString = ' String with tabs double-spaces and other whitespace areas. '; $MyCleanString = unspace($MySpacedString);
If you are willing to use a CPAN module then String::Util, or the somewhat more economical Text::Trim would be possible choices.
Trimming strings is one of those bike sheds that everyone likes to build! See the short perlmaven tutorial by @szabgab for a small sample of TIMTOWDI fun.
sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
print trim($myString)
If your white space is just spaces, then the following code will remove all spaces:
$mystring =~ tr/ //ds;