Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,
I want to remove the spaces (if it more than 1) with a single space. I am using the following code and it is not working
.
$str ="Any help would be greatly appreciated"; $str =~ s/\s{2,}/\s/g;
I want this to return 'Any help would be greatly appreciated'.
Thanks,

Replies are listed 'Best First'.
Re: Replace consecutive whitespaces with single whitespace
by tilly (Archbishop) on Mar 26, 2009 at 05:56 UTC
    Your replacement needs to be a space. \s is not a way to write that.
    $str ="Any help would be greatly appreciated"; $str =~ s/\s+/ /g; print $str;
      To avoid Perl doing work when it doesn't have to, I prefer to write that as:
      $str =~ s/\s{2,}/ /g;
      Note also that using \s matches more than the space the OP mentioned. In particular, s/\s+/ /g or s/\s{2,}/ /g will replace one (two) or more newlines with a space.
        As for the newline issue, I thought of that, and then I thought that the OP quite possibly had data with tabs in it rather than multiple spaces. In that case you would want to match more than just spaces. You would also want to replace a single tab with a single space.

        Besides which, the extra work is negligible - if you care about that small of an efficiency then Perl is probably the wrong language to use in the first place.

Re: Replace consecutive whitespaces with single whitespace
by jwkrahn (Abbot) on Mar 26, 2009 at 06:23 UTC

    Another way to do it:

    $ perl -le' my $str = "Any help would be greatly appreciated"; $str =~ tr/ //s; print $str; ' Any help would be greatly appreciated
Re: Replace consecutive whitespaces with single whitespace
by lakshmananindia (Chaplain) on Mar 26, 2009 at 05:56 UTC

    Check with the following code

    $str ="Any help would be greatly appreciated + "; $str =~ s/(\s)+/$1/g; print $str;
    --Lakshmanan G.

    Your Attempt May Fail, But Never Fail To Make An Attempt

Re: Replace consecutive whitespaces with single whitespace
by Anonymous Monk on Mar 27, 2009 at 23:10 UTC
    Performance summary of discussed options, based on Javafan's initial contribution, because I was interested:
    our $str = "x " x 1000; cmpthese -1, { single => sub { local $_ = $::str; s/\s+/ /g; }, multiple => sub { local $_ = $::str; s/\s{2,}/ /g; }, translate => sub { local $_ = $::str; tr/ //s; }, capture1 => sub { local $_ = $::str; s/(\s)+/$1/g; }, capture2 => sub { local $_ = $::str; s/(\s){2,}/$1/g; }, }; __END__ Rate capture1 single capture2 multiple translate capture1 1321/s -- -71% -82% -84% -99% single 4567/s 246% -- -37% -43% -97% capture2 7244/s 448% 59% -- -10% -95% multiple 8071/s 511% 77% 11% -- -95% translate 160627/s 12057% 3417% 2117% 1890% --