Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

Why is this not working?

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

$data =~ tr/ +/ /;

print $data;
like image 260
TCM Avatar asked Oct 02 '10 18:10

TCM


People also ask

How do I replace multiple spaces with single space in bash?

Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use echo unquoted within command substitution to have bash remove the additional whitespace for your, e.g. $ foo="too many spaces."; bar=$(echo $foo); echo "$bar" too many spaces.

Which of the given commands can be used to replace the multiple occurrences of spaces with a single space?

Answer: Use the JavaScript replace() method.

How do I give a space in Perl?

You must escape the space character with a backslash (write "\ ") or use \s to specify whitespace that is part of the pattern. tells Perl to save its place in the string so that you can iterate through the string and match the same pattern multiple times.


1 Answers

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).

like image 146
eldarerathis Avatar answered Oct 20 '22 01:10

eldarerathis