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

I have a string where there is a single blank space between each letter and two blank spaces between each word.How do i remove the blank spaces between letters and retain only one space between the words.

Replies are listed 'Best First'.
Re: help me ---regarding string
by Utilitarian (Vicar) on Oct 06, 2009 at 08:02 UTC
    You could use a regex like the following.
    $spacyString=~ s/\s(\S)/$1/g;
    This removes any space followed by a non-space character.
    Edited to make work properly after morning coffee
      thanks a lot ...
Re: help me ---regarding string
by DrHyde (Prior) on Oct 06, 2009 at 09:49 UTC
    Are they spaces, or are they NULs that get rendered as spaces in whatever you're using to view the data? This is a common symptom of 16-bit character sets, in which case the solution is to do some Encode voodoo that I don't understand.
Re: help me ---regarding string
by biohisham (Priest) on Oct 06, 2009 at 08:55 UTC
    The idea is to look for spaces on word boundaries and remove them (i.e it monitors the transition of a word character into a non-word character and then removes the non-word character), you can also monitor the transition of a non-word character into a word character by detecting the word character boundary post a non-word character as in the second line.

    $string = "H e l l o P e r l p r i n t"; print $string for $string =~ s/\b[ ]//g; print $string for $string =~ s/[ ]\b//g; UPDATE:added non-capturing square brackets to account for more efficie +ncy after Anomalous Monk's enlightenment...
    An exercise question for you, what do you think the reason that running both the print lines above together would result in the following output, But running only a single line of either the two print statements works just fine?!
    Hello PerlprintHelloPerlprint

    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.
      Although perlprint asked only about blanks and letters, sometimes punctuation creeps in. The third alternative handles all non-blanks and avoids capturing:
      >perl -wMstrict -le "my $string = 'W h a t H o ? N o G o .'; (my $sqz1 = $string) =~ s{ [ ] \b }{}xmsg; print qq{'$sqz1'}; (my $sqz2 = $string) =~ s{ \b [ ] }{}xmsg; print qq{'$sqz2'}; (my $sqz3 = $string) =~ s{ [ ] (?![ ]) }{}xmsg; print qq{'$sqz3'}; " 'What Ho ? No Go .' 'What Ho? No Go.' 'What Ho? No Go.'
      Update:  (?![ ]) vice  (?=\S) in third example.
Re: help me ---regarding string
by tye (Sage) on Oct 06, 2009 at 13:48 UTC
Re: help me ---regarding string
by ikegami (Patriarch) on Oct 06, 2009 at 15:06 UTC

    Are you sure your text isn't encoded using UTF-16 or similar?

    use Encode qw( decode ); my $text = decode('UCS-2le', "a\0b\0c\0 \0d\0e\0f\0"); print("$text\n"); # abc def