Perl: function to trim string leading and trailing whitespace

后端 未结 10 1857
深忆病人
深忆病人 2021-02-01 00:12

Is there a built-in function to trim leading and trailing whitespace such that trim(\" hello world \") eq \"hello world\"?

相关标签:
10条回答
  • 2021-02-01 00:50

    This is available in String::Util with the trim method:

    Editor's note: String::Util is not a core module, but you can install it from CPAN with [sudo] cpan String::Util.

    use String::Util 'trim';
    my $str = "  hello  ";
    $str = trim($str);
    print "string is now: '$str'\n";
    

    prints:

    string is now 'hello'

    However it is easy enough to do yourself:

    $str =~ s/^\s+//;
    $str =~ s/\s+$//;
    
    0 讨论(0)
  • 2021-02-01 00:51

    According to this perlmonk's thread:

    $string =~ s/^\s+|\s+$//g;
    
    0 讨论(0)
  • 2021-02-01 00:52

    No, but you can use the s/// substitution operator and the \s whitespace assertion to get the same result.

    0 讨论(0)
  • 2021-02-01 01:01

    I also use a positive lookahead to trim repeating spaces inside the text:

    s/^\s+|\s(?=\s)|\s+$//g
    
    0 讨论(0)
提交回复
热议问题