I know, this question was asked more than 7 years ago, but I would
like to post a sub that I wrote that does exactly what you want:

sub CollapseWhitespace{@_ or return'';my$T=shift;defined$T or return'';my$L=length($T);$L or return'';my$c;my$N=0;my$P =0;my$U=1;for(my$i=0;$i<$L;$i++){$c=vec($T,$i,8);if($c<33){ $U=0;if($N++==1){vec($T,$P++,8)=32;}}else{$N=0;$U or vec($T ,$P,8)=$c;$P++;}}return$U?$T:substr($T,0,$P);}

^^ This looks a bit obfuscated, so here is a nicer expanded version:

############################################################## # # This function removes single instances of whitespace and # converts multiple adjacent whitespace characters to a single # space. In this function, "whitespace" is defined as a character # whose ASCII value is less than 33. (This includes many special # characters such as new line characters, nul, bel, etc.) # # Usage: STRING = CollapseWhitespace(STRING) # # Example: # CollapseWhitespace("\n\t abc 123 xxx\n") --> " abc123 xxx" # sub CollapseWhitespace { @_ or return ''; my $T = shift; defined $T or return ''; my $L = length($T); $L or return ''; my $c; my $N = 0; # consecutive whitespace counter my $P = 0; # target pointer to overwrite original str $T my $U = 1; # string length will be left unchanged for (my $i = 0; $i < $L; $i++) { $c = vec($T, $i, 8); if ($c < 33) { $U = 0; if ($N++ == 1) { vec($T, $P++, 8) = 32; } } else { $N = 0; $U or vec($T, $P, 8) = $c; $P++; } } return $U ? $T : substr($T, 0, $P); }

In reply to Re: Removing extra spaces by harangzsolt33
in thread Removing extra spaces by rickoy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.