I would do it sequentially. Starting with your first question, I'd remove extra whitespace.
#!/usr/bin/perl -l use strict; use warnings; my $str = "this is an example"; $str =~ s/\s+/ /g; print $str;

I tried a bunch of different methods, but this was the most consistent, easiest way that I could find.

Update: I modified the code from String::Trim so that it only removes extra whitespace from within the string:
#!/usr/bin/perl -l use strict; my $str = "This is a start, but not a finished product howe +ver. "; my @str = ('This is a start, ', 'but not a finished product + however. '); trim($str); trim(@str); print $str; print @str; sub trim { my $t =~ s/\s+/ /g; if (defined wantarray) { @_ = (@_ ? @_ : $_); if (ref $_[0] eq 'ARRAY') { @_ = @{ $_[0];}; foreach $_ (@_) { s/\s+/ /g if defined $_ } return \@_; } elsif (ref $_[0] eq 'HASH') { foreach my $k (keys %{$_[0];}) { (my $nk = $k) =~ s/\s+/ /g; if (defined $_[0]->{$k}) { ($_[0]->{$nk} = $_[0]->{$k}) =~ s/\s+/ /g; } else { $_[0]->{$nk} = undef; } delete $_[0]->{$k} unless $k eq $nk; } } else { for (@_ ? @_ : $_) { s/\s+/ /g if defined $_ } } return wantarray ? @_ : $_[0]; } else { if (ref $_[0] eq 'ARRAY') { for (@{ $_[0] }) { s/\s+/ /g if defined $_ } } elsif (ref $_[0] eq 'HASH') { foreach my $k (keys %{ $_[0] }) { (my $nk = $k) =~ s/\s+/ /g; if (defined $_[0]->{$k}) { ($_[0]->{$nk} = $_[0]->{$k}) =~ s/\s+/ /g; } else { $_[0]->{$nk} = undef; } delete $_[0]->{$k} unless $k eq $nk } } else { for (@_ ? @_ : $_) { s/\s+/ /g if defined $_ } } } }

In reply to Re: regexp: removing extra whitespace by Khen1950fx
in thread regexp: removing extra whitespace by perlmax

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.