#!/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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |