Perl: function to trim string leading and trailing whitespace

后端 未结 10 1862
深忆病人
深忆病人 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+$//;
    

提交回复
热议问题