How do I remove white space in a Perl string?

后端 未结 12 1832
离开以前
离开以前 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 10:01

    I suggest that you make use of the Text::Trim module, which provides ltrim, rtrim, and trim, all of which will trim the parameters passed, or $_ if you give no parameters. It's not a core module so it may need installing

    0 讨论(0)
  • 2020-12-31 10:02

    Try this:

    # Delete leading/trailing whitespace.
    $string =~ s/^\s+|\s+$//g;
    
    0 讨论(0)
  • 2020-12-31 10:07

    Remove all spaces in a string:

    $string =~ s/ //g;
    
    0 讨论(0)
  • 2020-12-31 10:09

    Just looking over your program, I found 3 spots that could be improved or fixed.

    I apologize if my code doesn't format well. :-(

    In your function parse_block(...), there are 3 items that need attention.

    @attribs = $attribs =~ /\s*(\w+\s+=\s+\w+\s+|\w+\s+=\s+".*?"|\w+\s+=\s+<.*?>)\s*/g;
    

    To eliminate the white space after vid => '6 ', just don't include the \s+ at the end of your first sub-regex.

    Write it as:

    @attribs = $attribs =~ /\s*(\w+\s+=\s+\w+|\w+\s+=\s+".*?"|\w+\s+=\s+<.*?>)\s*/g;  
    
    $value = [ parse_type_value_specifier( $start_tail ) ];  
    

    You want this instead:

    $value = [ parse_type_value_specifier( $value ) ]; 
    

    (Note that the parameter to the function should be $value and not $start_tail.) You probably didn't notice this.

    In the loop for @attributes, the 'else' in the if/else condition excutes when the 'value' has a plain value, (no "" or <...> items in 'value').

    Update: Changed parameter in

    parse_type_value_specifier(...)
    to $value. It was (incorrectly) stated as $attrib.

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

    Remove spaces from variable $test (eq rtrim(ltrim(@sStr)) from Transact SQL:

    $test =~s/^\s*(\S*)\s*$/$1/;
    
    0 讨论(0)
  • 2020-12-31 10:11

    Another potential alternative solution is Text::Trim from CPAN, which will "remove leading and/or trailing whitespace from strings". It has a trim function which may suit your needs.

    0 讨论(0)
提交回复
热议问题