Perl: function to trim string leading and trailing whitespace

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

    For those that are using Text::CSV I found this thread and then noticed within the CSV module that you could strip it out via switch:

    $csv = Text::CSV->new({allow_whitespace => 1});
    

    The logic is backwards in that if you want to strip then you set to 1. Go figure. Hope this helps anyone.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-02-01 00:43

    Complete howto in the perfaq here: http://learn.perl.org/faq/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning-end-of-a-string-

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

    One option is Text::Trim:

    use Text::Trim;
    print trim("  example  ");
    
    0 讨论(0)
  • 2021-02-01 00:48

    Apply: s/^\s*//; s/\s+$//; to it. Or use s/^\s+|\s+$//g if you want to be fancy.

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

    Here's one approach using a regular expression:

    $string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace
    

    Perl 6 will include a trim function:

    $string .= trim;
    

    Source: Wikipedia

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