How can I replace multiple whitespace with a single space in Perl?

前端 未结 3 1600
心在旅途
心在旅途 2021-02-19 06:17

Why is this not working?

$data = \"What    is the STATUS of your mind right now?\";

$data =~ tr/ +/ /;

print $data;
3条回答
  •  离开以前
    2021-02-19 06:28

    Use $data =~ s/ +/ /; instead.

    Explanation:

    The tr is the translation operator. An important thing to note about this is that regex modifiers do not apply in a translation statement (excepting - which still indicates a range). So when you use
    tr/ +/ / you're saying "Take every instance of the characters space and + and translate them to a space". In other words, the tr thinks of the space and + as individual characters, not a regular expression.

    Demonstration:

    $data = "What    is the STA++TUS of your mind right now?";
    
    $data =~ tr/ +/ /;
    
    print $data; #Prints "What    is the STA  TUS of your mind right now?"
    

    Using s does what you're looking for, by saying "match any number of consecutive spaces (at least one instance) and substitute them with a single space". You may also want to use something like
    s/ +/ /g; if there's more than one place you want the substitution to occur (g meaning to apply globally).

提交回复
热议问题