How do I remove white space in a Perl string?

后端 未结 12 1831
离开以前
离开以前 2020-12-31 09:34

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

相关标签:
12条回答
  • 2020-12-31 09:47
    $myString =~ s/^\s*(.*?)\s*$/$1/;
    

    This will trim whitespace from both sides.

    from just the right:

    $myString =~ s/\s*$//;
    
    0 讨论(0)
  • 2020-12-31 09:53
    sub trim
    {
        my $str = $_[0];
        $str=~s/^\s+|\s+$//g;
        return $str;
    }
    
    print trim(" 4 ");
    
    0 讨论(0)
  • 2020-12-31 09:53

    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.

    -- routine

    sub unspace { my @stringer = @_ ? @_ : $; $ = join( ' ', split(' ')) for @stringer; return wantarray ? @stringer : "@stringer"; }

    -- usage

    $MySpacedString = ' String with tabs double-spaces and other whitespace areas. '; $MyCleanString = unspace($MySpacedString);

    0 讨论(0)
  • 2020-12-31 09:53

    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.

    0 讨论(0)
  • 2020-12-31 09:56
    sub trim($)
    {
        my $string = shift;
        $string =~ s/^\s+//;
        $string =~ s/\s+$//;
        return $string;
    }
    
    
    print trim($myString)
    
    0 讨论(0)
  • 2020-12-31 10:00

    If your white space is just spaces, then the following code will remove all spaces:

    $mystring =~ tr/ //ds;
    
    0 讨论(0)
提交回复
热议问题