Perl: function to trim string leading and trailing whitespace

后端 未结 10 1976
深忆病人
深忆病人 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:37

    There's no built-in trim function, but you can easily implement your own using a simple substitution:

    sub trim {
        (my $s = $_[0]) =~ s/^\s+|\s+$//g;
        return $s;
    }
    

    or using non-destructive substitution in Perl 5.14 and later:

    sub trim {
       return $_[0] =~ s/^\s+|\s+$//rg;
    }
    

提交回复
热议问题